#include <iostream>
#include <thread>
#include <mutex>//锁
using namespace std;
mutex g_mutex;
void threadPrint(int threadIndex)
{
for (int i = 0; i < 4; i++)
{
g_mutex.lock();
cout << "hello other<"<<threadIndex<<"> thread "<< endl;
g_mutex.unlock();
}
}
void mainPrint()
{
for (int i = 0; i < 4; i++)
{
g_mutex.lock();
cout << "hello main thread" << endl;
g_mutex.unlock();
}
}
int main()
{
//定义线程数组
thread threadPrintArray[3];
for (int i = 0; i < 3; i++)
{
threadPrintArray[i]=thread(threadPrint, i*100);
}
//使用线程
for (int i = 0; i < 3; i++)
{
threadPrintArray[i].detach();
}
//主线程
mainPrint();
//防止程序退出
getchar();
return 0;
}
Server - 线程锁
于 2019-08-07 20:20:17 首次发布