C++不加锁的多线程实例
#include <iostream>
#include <thread>
using namespace std;
int num = 100;
void fun1() {
if (num > 0) {
num = num - 1;
this_thread::sleep_for(chrono::milliseconds(10));
printf("the num=%d\n", num);
}
else
{
printf("the num = 0");
}
}
int main() {
thread threads[20];
for (int i=0;i<20;i++)
{
threads[i]= thread(fun1);
}
cout << "main thread" << endl;
for (int i=0; i<20; i++)
{
threads[i].join();
}
return 0;
}
显示的结果如下:
结果输出全是80,不符合需求。需要在线程的具体方法中添加锁,代码如下:
#include <iostream>
#include <thread>
#include <mutex>
using namespace std;
int num = 100;
mutex mu;
void fun1() {
mu.lock(); //手动加锁
if (num > 0) {
num = num - 1;
this_thread::sleep_for(chrono::milliseconds(10));
printf("the num=%d\n", num);
}
else
{
printf("the num = 0");
}
mu.unlock(); //手动解锁
}
int main() {
thread threads[20];
for (int i=0;i<20;i++)
{
threads[i]= thread(fun1);
}
cout << "main thread" << endl;
for (int i=0; i<20; i++)
{
threads[i].join();
}
return 0;
}
除了手动加锁和解锁外,C++也为我们提供了更便捷的使用方式:
lock_guard<mutex> lock(mu); //当前函数结束,会自动释放锁
#include <mutex>
recursive_mutex mut; //同一个线程可以多次添加锁
//不推荐使用,一旦爆发问题,很难修复。