BlockCount简介
BlockCount,障碍物个数。
之前通过一个Block可以阻塞线程。但是当一个线程,需要多个条件都满足时,才能继续运行。这怎么办呢?这个BlockCount就是用来干这个的。
BlockCount使用
BlockCount的使用,和Block类似。阻塞线程,使用block函数。释放线程,使用release函数。但是比Block多出来的功能是,使用completed函数,表示阻塞线程的东西少了一个。当阻塞线程的东西为0时,被BlockCount阻塞的线程才开始运行。
下面的程序,讲述三个线程A,B,C同时售票。但是A需要等到B和C都售票完毕后,再开始售票。
#include <OpenThreads/Thread>
#include <OpenThreads/Atomic>
#include <OpenThreads/Block>
#include <iostream>
#include <string>
OpenThreads::Atomic g_ticketCounts(150);
OpenThreads::BlockCount g_blockCount(2);
class TicketSellThread : public OpenThreads::Thread
{
public:
TicketSellThread(const std::string& threadName) : _name(threadName){}
virtual void run()
{
//A先阻塞自己
if ( _name == std::string("A") )
{
g_blockCount.reset();
g_blockCount.block();
}
for (int i = 0; i < 50; i++)
{
std::cout << _name << " sell " << --g_ticketCounts << std::endl;
}
//B和C完成自己的循环后,设置block完成一次。
//因为BlockCount设置为2,所以当B和C都完成后,A得以运行。
if (_name != std::string("A"))
{
g_blockCount.completed();
}
}
private:
std::string _name;
};
int main(int argc, char** argv)
{
TicketSellThread ticketSellThreadA("A");
ticketSellThreadA.start();
TicketSellThread ticketSellThreadB("B");
ticketSellThreadB.start();
TicketSellThread ticketSellThreadC("C");
ticketSellThreadC.start();
while(ticketSellThreadA.isRunning())
OpenThreads::Thread::YieldCurrentThread();
while(ticketSellThreadB.isRunning())
OpenThreads::Thread::YieldCurrentThread();
while(ticketSellThreadC.isRunning())
OpenThreads::Thread::YieldCurrentThread();
return 0;
}