#include <iostream>
#include <thread>
#include <mutex>
#if _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
using namespace std;
mutex mu; //线程互斥对象
int totalNum = 20;
void thread01()
{
while (totalNum > 0)
{
mu.lock();//同步数据锁
cout << "thread01="<<totalNum << endl;
totalNum--;
#if _WIN32
Sleep(100);
#else
//1s = 1000ms
//1ms = 1000μs
//1μs = 1000ns
usleep(1000*100);
#endif
mu.unlock(); //解除锁定
}
}
void thread02()
{
while (totalNum > 0)
{
mu.lock();
cout << "thread02="<<totalNum << endl;
totalNum--;
#if _WIN32
Sleep(100);
#else
//1s = 1000ms
//1ms = 1000μs
//1μs = 1000ns
usleep(1000*100);
#endif
mu.unlock();
}
}
int main()
{
thread task01(thread01);
thread task02(thread02);
task01.join();//主线程等待子线程执行完毕
task02.join();//主线程等待子线程执行完毕
//task01.detach();
//task02.detach();
//int n;
//cin>>n;
return 0;
}
c++多线程
最新推荐文章于 2024-08-21 09:33:26 发布