信号量我感觉可以实现线程之间传递和唤醒。很有意思的一种线程实现和线程同步。
#include
#include
#include
#include<condition_variable>
using namespace std;
class semaphone
{
public:
semaphone(unsigned int count) :count(count) {}
void wait()
{
std::unique_lockstd::mutex lk(mtx);
count–;
while (count < 0)
{
con.wait(lk);
}
}
void signal()
{
unique_lockstd::mutex lg(mtx);
if (++count<=0)//++count<=0 肯定有线程在等待。
{
con.notify_one();
}
}
private:
std::mutex mtx;
std::condition_variable con;
int count;
};
semaphone plate(1), apple(1), orange(1);
void father()
{
while (true)
{
plate.wait();
cout << “plate a apple” << endl;
apple.signal();
}
}
void mather()
{
while (true)
{
plate.wait();
cout << “plate a orange” << endl;
orange.signal();
}
}
void sun()
{
while (true)
{
apple.wait();
cout << “get a apple” << endl;
plate.signal();
}
}
void daughter()
{
while (true)
{
orange.wait();
cout << “get a orange” << endl;
plate.signal();
}
}
int main()
{
thread t1(father), t2(mather), t3(sun), t4(daughter);
t1.join();
t2.join();
t3.join();
t4.join();
system(“pause”);
return 0;
}
C++11信号量
最新推荐文章于 2023-10-07 11:28:07 发布