作为一个学习练习,我只是尝试使用C++ 标准提供的和其他一些东西来创建一个Semaphore
类。std::mutex
我的信号量应该允许尽可能多readLock()
的,但是writeLock()
只有在所有读取都解锁后才能获取。
//Semaphore.h
#include <mutex>
#include <condition_variable>
class Semaphore{
public:
Semaphore();
void readLock(); //increments the internal counter
void readUnlock(); //decrements the internal counter
void writeLock(); //obtains sole ownership. must wait for count==0 first
void writeUnlock(); //releases sole ownership.
int count; //public for debugging
private:
std::mutex latch;
std::unique_lock<std::mutex> lk;
std::condition_variable cv;
};
//Semaphore.cpp
#include "Semaphore.h"
#include <condition_variable>
#include <iostream>
using namespace std;
Semaphore::Semaphore() : lk(latch,std::defer_lock) { count=0; }
void Semaphore::readLock(){
latch.lock();
++count;
latch.unlock();
cv.notify_all(); //not sure if this needs to be here?
}
void Semaphore::readUnlock(){
latch.lock();
--count;
latch.unlock();
cv.notify_all(); //not sure if this needs to be here?
}
void Semaphore::writeLock(){
cv.wait(lk,[this](){ return count==0; }); //why can't std::mutex be used here?
}
void Semaphore::writeUnlock(){
lk.unlock();
cv.notify_all();
}
我的测试程序将writeLock()
信号量,启动一堆线程,然后释放信号量。紧接着,主线程将writeLock()
再次尝试信号量。这个想法是,当信号量被解锁时,线程将readLock()
它并阻止主线程做任何事情,直到它们全部完成。当它们都完成并释放信号量时,主线程可以再次获得访问权限。我意识到这可能不一定会发生,但这是我正在寻找的案例之一。
//Main.cpp
#include <iostream>
#include <thread>
#include "Semaphore.h"
using namespace std;
Semaphore s;
void foo(int n){
cout << "Thread Start" << endl;
s.readLock();
this_thread::sleep_for(chrono::seconds(n));
cout << "Thread End" << endl;
s.readUnlock();
}
int main(){
std::srand(458279);
cout << "App Launch" << endl;
thread a(foo,rand()%10),b(foo,rand()%10),c(foo,rand()%10),d(foo,rand()%10);
s.writeLock();
cout << "Main has it" << endl;
a.detach();
b.detach();
c.detach();
d.detach();
this_thread::sleep_for(chrono::seconds(2));
cout << "Main released it" << endl;
s.writeUnlock();
s.writeLock();
cout << "Main has it " << s.count << endl;
this_thread::sleep_for(chrono::seconds(2));
cout << "Main released it" << endl;
s.writeUnlock();
cout << "App End" << endl;
system("pause"); //windows, sorry
return 0;
}
该程序抛出一个异常,说“unlock of unowned mutex”。我认为错误在writeLock()
or中writeUnlock()
,但我不确定。谁能指出我正确的方向?
编辑:在构造函数中std::defer_lock
初始化时丢失lk
,但是它没有解决我得到的错误。正如评论中提到的,这不是信号量,我为造成的混乱道歉。为了重申这个问题,这是我得到的输出(括号中的内容只是我的评论,实际上并不在输出中):
App Launch
Thread Start
Thread Start
Main has it
Thread Start
Thread Start
Thread End (what?)
Main released it
f:\dd\vctools\crt_bld\self_x86\crt\src\thr\mutex.c(131): unlock of unowned mutex
Thread End
Thread End
Thread End