#ifndef my_task_queue_h #define My_task_queue_h #include <queue> #include <boost/thread.hpp> #include <
boost/noncopyable.hpp> #include <boost/function.hpp>//using namespace boost;
using namespace Std;
typedef boost::function<void (void) > My_task;
Task Queue class Task_queue:boost::noncopyable {private:std::queue<my_task> my_queue;
Boost::condition_variable_any cond;
Boost::mutex My_mutex; Public:void push_task (const My_task & Task_func) {//Plus mutex boost::unique_lock<boost::mutex> lo
CK (My_mutex);
My_queue.push (Task_func);
Notify other threads to start cond.notify_one ();
My_task Get_task () {//Plus Mutex lock boost::unique_lock<boost::mutex> Lock (My_mutex);
if (My_queue.size () ==0) {//If there are no tasks in the queue, wait for the mutex cond.wait (lock);
//point to Queue Header My_task task (My_queue.front ());
Out queue My_queue.pop ();
return task; int Get_size () {return my_queue.size ();
}
};
#endif
#ifndef my_thread_pool_h #define My_thread_pool_h #include <boost/thread.hpp> #include <boost/ noncopyable.hpp> #include <boost/function.hpp> #include "my_task_queue.h" #include <iostream> using
namespace Std;
Class My_thread_pool:boost::noncopyable {private://thread queue Task_queue my_queue;
Thread group Boost::thread_group My_thread_group;
int thread_num;
volatile bool Is_run;
void Run () {while (Is_run) {cout<< "Run" <<endl;
The task of processing thread pools has been my_task task=my_queue.get_task ();
Task ();
} public:my_thread_pool (int num): thread_num (num), Is_run (false) {};
~my_thread_pool () {};
void Init () {is_run=true;
if (thread_num<=0) {return; for (int i=0;i<thread_num;++i) {//Generate multiple threads, bind the Run function, add to Thread group my_thread_group.add_t Hread (New Boost::threaD (Boost::bind (&my_thread_pool::run,this));
}//Stop thread pool void Stop () {is_run=false;
}//Add task void post (const my_task &task) {my_queue.push_task (Task);
} void Wait () {my_thread_group.join_all ();
}
};
#endif
#include "my_task_queue.h"
#include "my_thread_pool.h"
#include <iostream>
#include <cstdlib >
using namespace std;
void Print_task (int i)
{
cout<< "I am Task" <<i<< "number:" <<endl;
}
Use the boost thread pool to compile parameters plus-lboost_thread
int main (int argc, char** argv) {
my_thread_pool TP (4);
Tp.init ();
My_task task[4];
for (int i=0;i<4;i++)
{
//Generate thread task, type is function pointer boost::function<void (void) >
task[i]=boost::bind ( PRINT_TASK,I+1);
To process
Tp.post (Task[i]) in a thread pool;
Wait for thread pool processing to complete.
tp.wait ();
return 0;
}