#include <iostream>
using namespace std;
#include <boost/thread.hpp>
/*
Ttile: 一个简单的信号量
Purpose:
[1]更快的响应事件处理。
Description:
[1]技术可行性测试。
Dependencies:
[1]boost 1.61
Test Environment:
[1]VS2013 Update5.
Situation:
[1]等待有事件了处理事件,原来的代码。
while(!stopWait)
{
if(hasEvent())
processEvent;
else
sleep(a while);
}
改进后应该是这样的
do
{
wait();
if(hasEvent())
processEvent;//启动子线程来处理具体事件
}while(!stopWait);
terminateAllProcess;
*/
namespace kagula
{
class Semaphore
{
public:
Semaphore() :_hasEvent(false){}
void signal()
{
boost::lock_guard<boost::mutex> lock(_mutex);
_hasEvent = true;
_condition.notify_one();
}
void wait()
{
boost::unique_lock<boost::mutex> lock(_mutex);
if (!_hasEvent)
{
_condition.wait(lock);
}
}
bool wait(unsigned nMillSec)
{
boost::unique_lock<boost::mutex> lock(_mutex);
if (_hasEvent)
{
return true;
}
return _condition.timed_wait(lock, boost::posix_time::millisec(nMillSec));
}
void reset() {
_hasEvent = false;
}
private:
bool _hasEvent;//如果同时存在多个event,这里可以用std::queue<T>代替。
boost::mutex _mutex;
boost::condition_variable _condition;
};//class
}//namespace
//
kagula::Semaphore g_semaphore;
boost::mutex g_prompt;
void prompt(std::string msg)
{
boost::lock_guard<boost::mutex> l(g_prompt);
cout << msg << endl;
}
void branchTask(std::string taskName)
{
for (unsigned i = 0; i < 5;i++)
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
prompt(taskName);
}
prompt("");
g_semaphore.signal();
}
int main(int argc, char** argv)
{
[](){
cout << "测试:等待某个处理完成后继续运行" << endl;
boost::thread t([](){
cout << "start work." << endl;
boost::thread t(branchTask,"a");
prompt( "Wait work over!" );
g_semaphore.wait();
prompt("After a, Go on...");
});
t.join();
}();
cout << "===================================" << endl;
[](){
g_semaphore.reset();
cout << "测试:等待某个处理,超时后继续运行" << endl;
boost::thread t([](){
prompt("start work." );
boost::thread t(branchTask, "b");
cout << "Wait work over!" << endl;
if (g_semaphore.wait(3000))
{
prompt("A piece work has done!");
}
else
{
prompt("A piece work has timeout");
t.interrupt();
t.join();
prompt("End the task!");
}
prompt("After b,Go on...");
});
t.join();
}();
cout << "===================================" << endl;
[](){
g_semaphore.reset();
cout << "测试:不再等待某个处理,要求等待处理结束的线程马上返回!" << endl;
boost::thread t([](){
prompt("start work.");
boost::thread t(branchTask, "c");
prompt("Wait work c over!");
g_semaphore.wait();
prompt("Worker 还在工作? 结束它,否则本线程结束了,子线程还在运行。");
if (t.joinable())
{
t.interrupt();
t.join();
}
//如果有多个,需要把子(任务)线程加入到线程组boost::thread_group中,然后join_all等待全部线程返回。
cout << "After c,Go on..." << endl;
});
if (t.joinable())
{
prompt("i want break wait!");
g_semaphore.signal();//让线程不再wait.
t.join();
prompt("break c success!");
}
else {
prompt("The thread is not joinable!");
}
}();
cout << endl << "Please input any character to continue..." << endl;
cin.get();
return 0;
}
一个简单的信号量
最新推荐文章于 2023-10-27 17:54:58 发布