Boost logo

Boost Users :

From: Ruediger Berlich (ruediger.berlich_at_[hidden])
Date: 2008-08-05 19:36:19


Hi there,

I'm trying to find a way to let a number of threads start execution
simultaneously, and in any case not before a certain condition has come
true. I would also like to terminate them within a relatively short time
frame.

I can not use the Boost.Thread barrier class, as I do not know the number of
threads in advance (users register consumer-type objects, and I do not know
how many there will be). I also believe I do not have to use a condition
variable, as the different threads need to synchronize their access to a
data ressource anyway, and I can use the same mutex to block them in the
beginning.

I have thus come up with something like the code quoted below. Are there
easier ways to do this with the Boost.Thread library ?

One of the problems (which seems to be unrelated to the code below) is that
the three threads do not get called equally often. In one run, one thread
was called 14564 times, another 1607 times and the third one 8676 times.

Thanks and Best Regards,
Ruediger

/***********************************************************************/

#include <iostream>

#include <boost/cstdint.hpp>
#include <boost/bind.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition.hpp>
#include <boost/thread/condition_variable.hpp>
#include <boost/thread/thread.hpp>

using namespace std;

class test
{
public:
    test()
        :lock(helloMutex_),
         jointData_(0),
         MAXJOINTDATA(10000),
         thread1(boost::bind(&test::sayHello, this)),
         thread2(boost::bind(&test::sayHello, this)),
         thread3(boost::bind(&test::sayHello, this))
        { /* nothing */ }

    void startAndStopThreads(){
        lock.unlock();

        while(true){
            boost::unique_lock<boost::mutex> local_lock(helloMutex_);

            if(jointData_ >= MAXJOINTDATA){
                thread1.interrupt();
                thread2.interrupt();
                thread3.interrupt();

                break;
            }
        }

        thread1.join();
        thread2.join();
        thread3.join();
    }

    void sayHello(){
        for(;;){
            if(boost::this_thread::interruption_requested()) break;

            boost::unique_lock<boost::mutex> local_lock(helloMutex_);
            std::cout << "Hello world Nr. " << jointData_++
                      << " from thread " << boost::this_thread::get_id() << std::endl;
        }
    }

private:
    boost::mutex helloMutex_;
    boost::unique_lock<boost::mutex> lock;

    uint32_t jointData_;
    const uint32_t MAXJOINTDATA;

    boost::thread thread1, thread2, thread3;
};

main(){
    test Test;
    Test.startAndStopThreads();

    std::cout << "Done ..." << std::endl;
}


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net