C++11实现信号量semaphore
描述
1)信号量是一种线程/进程间同步的一种手段,可以用来管理有限资源的访问;
2)互斥锁主要用来进行互斥的,而信号量则是主要用来同步的;
3)从使用上来说,互斥锁的lock和unlock必须在同一个线程;而信号量的wait和signal可以在不同的线程;
典型的线程同步代码如下所示:
#include"semaphore.h"
#include<thread>
#include<iostream>
semaphore sem(0);
void func1() {
// do something
std::this_thread::sleep_for(std::chrono::seconds(2));
std::cout << "func1" << std::endl;
sem.signal();
}
void func2() {
sem.wait();
//do something
std::cout << "func2" << std::endl;
}
int main() {
std::thread thread1(func1);
std::thread thread2(func2);
if (thread1.joinable())
thread1.join();
if (thread2.joinable())
thread2.join();
}
源码
semaphore.h
#pragma once
#include<mutex>
#include<condition_variable>
class semaphore {
public:
semaphore(long count = 0) :count(count) {}
void wait() {
std::unique_lock<std::mutex>lock(mx);
cond.wait(lock, [&]() {return count > 0; });
--count;
}
void signal() {
std::unique_lock<std::mutex>lock(mx);
++count;
cond.notify_one();
}
private:
std::mutex mx;
std::condition_variable cond;
long count;
};