xxx.h文件:
int count;
void threadA();
void threadB();
xxx.cpp文件:
/* 引入头文件#include <thread> 引入std::mutex _mutex; */
//1.新建线程A
std::thread t1(&Login::threadA,this);//取Login的地址
t1.detach();//设置主线程和子线程互不影响
//2.新建线程B
std::thread t2(&Login::threadB,this);//取Login的地址
t2.detach();//设置主线程和子线程互不影响
//3.两个线程对同一个资源count进行操作
count = 0;
void Login::threadA()
{
while (count < 10) {
//加锁
_mutex.lock();
count++;
//设置本线程等待3秒
this_thread::sleep_for(chrono::seconds(3));
CCLOG("A Thread Id is: %x,count value is %d",this_thread::get_id(),count);
//解锁
_mutex.unlock();
}
}
void Login::threadB()
{
while (count < 10) {
//加锁
_mutex.lock();
count++;
//设置本线程等待3秒
this_thread::sleep_for(chrono::seconds(3));
CCLOG("B Thread Id is: %x,count);
//解锁
_mutex.unlock();
}
}