0

I want to implement thread pool using boost::thread class.

I am able to create the threads using below line.

boost::thread Consumer_1(consume); 

where consumer_1 is thread and consume is the function bound to it.

Above statement starts the thread as soon as it gets executed.

Now I just want to create the thread and do the binding run time.

I have not yet discovered the boost method to delay this binding.

Can anyone help on this?

Ashwani
  • 3,463
  • 1
  • 24
  • 31
Codelearner
  • 241
  • 2
  • 3
  • 16

1 Answers1

1

The binding can't be done later. For principal reasons—a thread of execution has to be executing something.

What you need to do is create a function, that will take jobs, represented as boost::function, from a queue and execute them. Than run this function in one or more threads.

I am not sure there is a thread-safe queue, but you can always use a regular std::deque with boost::condition_variable for waking up the threads and boost::mutex for locking the deque.

You might want to look at Boost.Asio too. See also here.

Community
  • 1
  • 1
Jan Hudec
  • 73,652
  • 13
  • 125
  • 172
  • 1
    +1 For suggesting Asio. You probably don't want to use your own threadpool in production code. If you have to, check out Williams' 'C++ Concurrency in Action' book which has a whole chapter on the topic, discussing the many many things that you can do wrong. – ComicSansMS Aug 23 '13 at 10:18