Boost logo

Boost Users :

Subject: Re: [Boost-users] Thread object pointers. (solved)
From: Albert Schueller (schuelaw_at_[hidden])
Date: 2010-08-03 17:42:31


Tue Aug 3 14:40:40 PDT 2010

It's amazing how you stare at code for an hour, finally give up, post a
message to a mailing list, and 5 minutes later solve the problem.

The difference between the two listings is in the join()'s. In the
first the three thread objects are created and then the three join()'s
executed. In the second, it's thrd[0], join(), thrd[1], join(),
thrd[2], join(). I'm not entirely sure why this matters, but it did fix
the problem.

Hope somebody finds this little diversion useful...

Albert

> ///////////////////////////////////////////////////////////////////////////
> //LISTING 1
>
> #include <boost/thread/thread.hpp>
> #include <boost/thread/mutex.hpp>
> #include <iostream>
> #include <unistd.h>
> #include <cstdlib>
>
> boost::mutex io_mutex;
>
> struct count
> {
> count(int id) : id(id) { }
>
> void operator()()
> {
> int upause;
> for (int i = 0; i < 10; ++i)
> {
> upause = rand()%1000000;
> usleep(upause);
> boost::mutex::scoped_lock
> lock(io_mutex);
> std::cout << id << ": "
> << i << " paused " << upause << std::endl;
> }
> }
>
> int id;
> };
>
> int main(int argc, char* argv[])
> {
> boost::thread thrd1(count(1));
> boost::thread thrd2(count(2));
> boost::thread thrd3(count(3));
> thrd1.join();
> thrd2.join();
> thrd3.join();
> return 0;
> }
>
>
> ///////////////////////////////////////////////////////////////////////////
> //LISTING 2
>
> #include <boost/thread/thread.hpp>
> #include <boost/thread/mutex.hpp>
> #include <iostream>
> #include <unistd.h>
> #include <cstdlib>
>
> boost::mutex io_mutex;
>
> struct count
> {
> count(int id) : id(id) { }
>
> void operator()()
> {
> int upause;
> for (int i = 0; i < 10; ++i)
> {
> upause = rand()%1000000;
> usleep(upause);
> boost::mutex::scoped_lock
> lock(io_mutex);
> std::cout << id << ": "
> << i << "paused (" << upause << ")" << std::endl;
> }
> }
>
> int id;
> };
>
> int main(int argc, char* argv[])
> {
> int i;
> int num_thrds = 3;
> boost::thread *thrd[4];
>
// Change this:
> for(i=0;i<num_thrds;i++) {
> thrd[i] = new boost::thread(count(i+1));
> thrd[i]->join();
> }

// To this:
   for(i=0;i<num_thrds;i++) {
    thrd[i] = new boost::thread(count(i+1));
   }
   for(i=0;i<num_thrds;i++) {
    thrd[i]->join();
   }

>
> // deallocate thread objects
> for(i=0;i<num_thrds;i++) {
> delete thrd[i];
> }
>
> return 0;
> }
>


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