
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
#include #include <iostream> #include #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
#include #include <iostream> #include #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
join(); }
// To this:
for(i=0;i
// deallocate thread objects for(i=0;i
return 0; }