mutex,thread(c++11 windows linux三种方式)

时间:2022-06-05 14:34:03

一 c++11  windows linux三种方式

//#include <stdio.h>
//#include <stdlib.h>
//#include <unistd.h>
#include <windows.h>
//#include <pthread.h>
#include <mutex>
#include <thread>
#include <string.h> using namespace std;
char* buf[5]; //字符指针数组 全局变量
int pos; //用于指定上面数组的下标 //1.定义互斥量
//pthread_mutex_t mutex; // linux
mutex mtx; // C++11
HANDLE g_hMutex = INVALID_HANDLE_VALUE; // Win
void *task(void *p)
{
//3.使用互斥量进行加锁
//pthread_mutex_lock(&mutex); // linux
//mtx.lock(); // C++11
WaitForSingleObject(g_hMutex, INFINITE);//等待互斥量 Win buf[pos] = (char *)p; printf("task %d\r\n", pos);
//sleep(1); // linux
Sleep(500); // Win pos++; //4.使用互斥量进行解锁
//pthread_mutex_unlock(&mutex); // linux
//mtx.unlock(); // C++11
ReleaseMutex(g_hMutex);//释放互斥量 // Win return 0;
} int main(void)
{
//2.初始化互斥量, 默认属性
//pthread_mutex_init(&mutex, NULL); // linux
g_hMutex = CreateMutex(nullptr, false, nullptr); // Win //1.启动一个线程 向数组中存储内容
//pthread_t tid, tid2; // linux
//pthread_create(&tid, NULL, task, (void *)"woainia!"); // linux
//pthread_create(&tid2, NULL, task, (void *)"how"); // linux // CreateThread(nullptr,0...) // Win
thread th1(task, (void *)"woainia!"); // C++
thread th2(task, (void *)"how"); // C++ //2.主线程进程等待,并且打印最终的结果
//pthread_join(tid, NULL); // linux
//pthread_join(tid2, NULL); // linux th2.join(); // C++
th1.join(); // C++ //5.销毁互斥量
//pthread_mutex_destroy(&mutex); // linux
CloseHandle(g_hMutex); // Win Sleep(5000);
int i = 0;
printf("字符指针数组中的内容是:pos:%d \r\n", pos);
for (i = 0; i < pos; ++i)
{
printf("%d : %s \n", i, buf[i]);
}
printf("\n"); system("pause");
return 0;
}

mutex,thread(c++11 windows linux三种方式)

二、C++11 thread

//#include <cstdlib>
//#include <cstdio>
//#include <cstring>
#include <string>
#include <iostream>
#include <thread>
using namespace std; // 案例一
void my_print()
{
cout << "线程开始执行了!" << endl;
//...
//...
cout << "线程结束执行了!" << endl;
} // 案例二
class TA
{
public:
TA()
{
cout << "TA构造函数" << endl;
}
~TA()
{
cout << "~TA析构函数" << endl;
}
void operator()() // 必须重载() 因子线程需运行函数
{
cout << "线程operator开始执行了!" << endl;
//...
//...
cout << "线程operator结束执行了!" << endl;
} TA(const TA& ta)
{
cout << "TA拷贝构造函数" << endl;
} }; int main()
{
// 案例一 直接用函数当对象
//std::thread thobj(my_print);
////thobj.join();
//bool b = thobj.joinable();
//thobj.detach();
//b = thobj.joinable(); // 案例二 直接用类对象当对象
TA t;
std::thread thobj2(t);
thobj2.join(); // 此时子线程拷贝的对象 析构函数会在前台运行
//thobj2.detach(); // 此时子线程拷贝的对象 析构函数会在后台运行 // 案例三 lambda表达式
//auto my_thread = [] {
// cout << "lambda线程开始执行了!" << endl;
// //...
// //...
// cout << "lambda线程结束执行了!" << endl;
//};
//std::thread thobj3(my_thread);
//thobj3.join(); //std::thread thobj3([] {
// cout << "lambda线程开始执行了!" << endl;
// //...
// //...
// cout << "lambda线程结束执行了!" << endl;
//});
//thobj3.join(); printf("hello jadeshu...\n");
//system("pause");
return 0;
}

mutex,thread(c++11 windows linux三种方式)