mutex,thread

//#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

上一篇:大数据量数据库设计与优化方案(SQL优化)


下一篇:Ceph luminous 安装配置