/// \file PTQ2.cpp /// \brief This file demonstrates the use of PriorityThreadQueue, by creating a very large number of threads, and executing them all in order of decreasing priority. #include #include #include #include #include using namespace std; #include "PriorityThreadQueue.h" PriorityThreadQueue PTQ; boost::mutex io_mutex; bool flag; bool is_up() { boost::mutex::scoped_lock lock(io_mutex); return flag == true; } bool up() { boost::mutex::scoped_lock lock(io_mutex); flag = true; return true; } bool down() { boost::mutex::scoped_lock lock(io_mutex); flag = false; return false; } class Count { public: int sleep_time; int priority; void operator()(); Count(int id, int sleep_time, int priority) : id(id), sleep_time(sleep_time), priority(priority) { } int id; }; void Count::operator()() { PTQ.register_thread( id, priority); PTQ.request_cpu( id); down(); { boost::xtime xt; xtime_get( &xt, boost::TIME_UTC); xt.sec += sleep_time; boost::thread::sleep(xt); } for (int i = 0; i < 10; ++i) { std::cout << id << ": " << priority << ": " << i << std::endl; } //std::cerr << "calling release_cpu" << std::endl; PTQ.release_cpu( id); } int main(int argc, char* argv[]) { boost::thread_group tg; int i, j, id, sleep_time; id =0; for (i=10; i>0; --i) { sleep_time = (i==10)? 2:0; up(); for (j=0; j<=10-i; ++j, ++id) { tg.create_thread( Count( id, sleep_time, i)); while (is_up()) { boost::xtime xt; xtime_get( &xt, boost::TIME_UTC); xt.nsec += 1000000; // 1 msec boost::thread::sleep(xt); } } } tg.join_all(); return 0; }