/// \file PTQ.cpp /// \brief This demonstrates the use of PriorityThreadQueue by creating 10 threads with priorities from 1 through 10. Verbose output is specified, by the macro PTQVERBOSE. #include #include #include #include using namespace std; #define PTQVERBOSE 1 #include "PriorityThreadQueue.h" PriorityThreadQueue PTQ; boost::mutex up_mutex; boost::condition up_condition; bool is_up = false; boost::mutex down_mutex; boost::condition down_condition; bool is_down = false; boost::mutex start_all; boost::mutex cerr_mutex; bool up() { boost::mutex::scoped_lock up_lock(up_mutex); is_up = true; return false; } void wait_while_up() { boost::mutex::scoped_lock up_lock(up_mutex); if (is_up) { up_condition.wait( up_lock); } } bool down() { boost::mutex::scoped_lock down_lock(down_mutex); if (is_up) { is_up = false; up_condition.notify_one(); } //boost::mutex::scoped_lock up_lock(up_mutex); is_down = true; return false; } /// \brief This class is used in the example files PTQ.cpp and PTQ2.cpp class Count { public: int id; int sleep_time; int priority; void operator()(); Count(int id, int sleep_time, int priority) : id(id), sleep_time(sleep_time), priority(priority) { } }; void Count::operator()() { { boost::mutex::scoped_lock cerr_lock( cerr_mutex); std::cerr << "calling register thread with id = " << id << std::endl; if (PTQ.register_thread( id, priority) != 0) { std::cerr << "register thread did not work" << endl; } down(); std::cerr << "calling request cpu with id = " << id << std::endl; } PTQ.request_cpu( id); // cerr_mutex can't be locked, because this function blocks { boost::mutex::scoped_lock lock( start_all); } { boost::xtime xt; xtime_get( &xt, boost::TIME_UTC); xt.sec += sleep_time; std::cerr << "thread " << id << " is now executing" << endl; boost::thread::sleep(xt); } { boost::mutex::scoped_lock cerr_lock( cerr_mutex); for (int i = 0; i < 10; ++i) { std::cerr << id << ": " << i << std::endl; } std::cerr << "thread " << id << " is now done and will call relase_cpu" << endl; PTQ.release_cpu( id); } } int main(int argc, char* argv[]) { boost::thread_group tg; int i, sleep_time; { boost::mutex::scoped_lock lock( start_all); for (i=10; i>0; --i) { sleep_time = 5; up(); tg.create_thread( Count( i, sleep_time, i)); wait_while_up(); } } { boost::mutex::scoped_lock cerr_lock( cerr_mutex); cerr << "calling join all" << endl; } tg.join_all(); cerr << "Done!" << endl; return 0; }