
On Tue, Aug 3, 2010 at 3:10 PM, Albert Schueller
Tue Aug 3 14:10:04 PDT 2010
Hi all,
I'm trying to get up to speed on libboost's thread class using the tutorial information here:
http://www.drdobbs.com/cpp/184401518
I'm curious why the two programs below seem to behave differently. In LISTING 1, three threads are declared as thrd1, thrd2, and thrd3 explicitly and each loops 10 times with random length sleeps.
LISTING 2 is identical, except for the fact the three thread variables are allocated to boost::thread pointers.
When I run LISTING 1 it appears that the threads are acting independently as I would hope. When I run LISTING 2, it seems that the threads are not independent, but rather thrd1 does its job, followed by thrd2, followed by thrd3.
Am I not locking properly?
Any help would be appreciated.
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];
I would imagine it is because of this part:
for(i=0;i
join(); }
You are creating a thread, then immediately joining it, which means
that it needs to finish before the join() call completes, maybe do
this instead:
for(i=0;i
// deallocate thread objects for(i=0;i
return 0; }