c语言线程锁的原理开锁原理图,C++多线程之可重入锁
#include
#include
#include
using namespace std;
recursive_mutex re;
void task1()
{
re.lock();
cout << "處理任務1中..." << endl;
std::this_thread::sleep_for(1s);
re.unlock();
}
void task2()
{
re.lock();
cout << "處理任務2中..." << endl;
std::this_thread::sleep_for(1s);
re.unlock();
}
class ThreadBase
{
public:
virtual void Start()
{
is_exit = false;
th = std::thread(&ThreadBase::Main,this);
}
virtual void Stop()
{
is_exit = true;
Wait();
}
virtual void Wait()
{
if (th.joinable())
{
th.join();
}
}
bool get_exit()
{
return is_exit;
}
virtual void Main() = 0;
ThreadBase(int _i):i(_i) {}
virtual ~ThreadBase() {}
int i;
private:
std::thread th;
bool is_exit;
};
class MyThread:public ThreadBase
{
public:
MyThread(int i):ThreadBase(i) {}
~MyThread() override {}
void Main() override
{
for (;;)
{
//如果不是可重入鎖,那么得先開鎖然后才能執行task1,否則會造成死鎖
//但是如果開鎖,也就是在一個線程執行任務時,另一個線程也進來了,如果另一個線程執行了一會就結束了,肯定會
//釋放鎖,而實際上線程一的任務還沒執行完
re.lock();
cout << "線程" << i << "拿到了鎖" << endl;
task1();
task2();
re.unlock();
std::this_thread::sleep_for(1ms);
}
}
};
int main(int argc,char* argv[])
{
MyThread th_one(1);
th_one.Start();
th_one.Wait();
getchar();
return 0;
}
原文:https://www.cnblogs.com/SunShine-gzw/p/14530107.html
總結
以上是生活随笔為你收集整理的c语言线程锁的原理开锁原理图,C++多线程之可重入锁的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 根据银行卡号判断所属银行(部分资源网上抄
- 下一篇: RDLC 设置表的重复标题行(在每页中显