自学内容网 自学内容网

多线程中的一些概念

二元信号量

可以理解为一个通行令牌,当有一个线程A拿到后,其他线程只有等待,等到A通行结束后,会把令牌归还,其余线程自己去抢。c++20之前是没有这个玩意的,下面可以用互斥量和条件变量去是现实一个。

// semaphore.h
 #ifndef _SEMAPHORE_H
 #define _SEMAPHORE_H
 #include <mutex>
 #include <condition_variable>
 using namespace std;

 class Semaphore
 {
 public:
 Semaphore(long count = 0) : count(count) {}
 //V操作,唤醒
 void signal()
 {
 unique_lock<mutex> unique(mt);
 ++count;
 if (count <= 0)
 cond.notify_one();
 }
 //P操作,阻塞
 void wait()
 {
 unique_lock<mutex> unique(mt);
 --count;
 if (count < 0)
 cond.wait(unique);
 }

 private:
 mutex mt;
 condition_variable cond;
 long count;
 };
 #endif
 
 //semaphore.cc
  #include "semaphore.h"
 #include <thread>
 #include <iostream>
 using namespace std;

 Semaphore sem(0);

 void funA()
 {
 sem.wait();
 //do something
 cout << "funA" << endl;
 }

 void funB()
 {
 this_thread::sleep_for(chrono::seconds(1));
 //do something
 cout << "funB" << endl;
 sem.signal();
 }

 int main()
 {
 thread t1(funA);
 thread t2(funB);
 t1.join();
 t2.join();
 }

这里使用场景是一定可以保证函数B先执行,所以可以看出二元信号量可以用作线程之间通信或者同步使用。

信号号量

可以理解为多个通行令牌,理解和上面一样,无非是一次可以有多个线程通行

互斥量

和二元信号量的区别是,互斥量是线程A获取,必须A去释放,而二元信号量是进程里所有的其他线程都可以去抢夺释放

临界区


原文地址:https://blog.csdn.net/feng__shuai/article/details/142852115

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!