views:

107

answers:

2

This is the code to create a thread_group and execute all threads in parallel:

boost::thread_group group;
for (int i = 0; i < 15; ++i)
    group.create_thread(aFunctionToExecute);
group.join_all();

This code will execute all threads at once. What I want to do is to execute them all but 4 maximum in parallel. When on is terminated, another one is executed until there are no more to execute.

+2  A: 

Another, more efficient solution would be to have each thread callback to the primary thread when they are finished, and the handler on the primary thread could launch a new thread each time. This prevents the repetitive calls to timed_join, as the primary thread won't do anything until the callback is triggered.

James
Exactly what I was going to do. Now, just thinking about how to implement it in a sexy way :)Thx
Kensou
Finally end up with something like this:I have a threadpool in which I register all the jobs. Then, I create the n threads and pass as argument to each thread the threadpool. Each thread checks whether there are jobs left. If yes, just get one job to execute. Otherwise, the thread ends.This way, we just create n threads and not a thread per job (a job ends, a new thread is created).
Kensou
A: 

i have smthg like this:

    boost::mutex mutex_;
    boost::condition_variable condition_;
    const size_t throttle_;
    size_t size_;
    bool wait_;
    template <typename Env, class F>
    void eval_(const Env &env, const F &f) {
        {   
            boost::unique_lock<boost::mutex> lock(mutex_);
            size_ = std::min(size_+1, throttle_);
            while (throttle_ <= size_) condition_.wait(lock);
        }
        f.eval(env);
        {
            boost::lock_guard<boost::mutex> lock(mutex_);
            --size_; 
        }
        condition_.notify_one();
    }
aaa