views:

79

answers:

2
+1  Q: 

c++ multithread

I use c++ to implement a thread class. The code is in the following. I initialize two objects, wish it will start two threads (I use pthread_self() to look the thread Id). But the result shows that there is only one thread beside the main thread. I am a bit confused...

class Thread {
public:
  int mask;
  pthread_t thread;

  Thread( int );
  void start();
  static void * EntryPoint (void *);
  void Run();
};

Thread::Thread( int a) {
  mask =a; 
}

void Thread::Run() {

  cout<<"thread begin to run" <<endl;
  cout <<" Thread Id is: "<< pthread_self() << endl; // the same thread Id.       
}

void * Thread::EntryPoint(void * pthis) {
  cout << "entry" <<endl;
  Thread *pt = (Thread *) pthis;
  pt->Run();
}

void Thread::start() {

  pthread_create(&thread, NULL, EntryPoint, (void *)ThreadId );
  pthread_join(thread, NULL);
}

int main() {
  int input_array[8]={3,1,2,5,6,8,7,4};
  Thread t1(1);
  Thread t2(2);
  t1.start();  
  t2.start()
}
+4  A: 

You are seeing this behavior because you join with each of your threads immediately after you spawn them.

When you join with a thread, you block until the thread terminates.

James McNellis
A: 

You are spawning two threads, but the first thread is joined (and destroyed) before the second thread is spawned, so you have effectively only one thread running at a time. The way to fix this is:

  1. Create a separate join function that invokes join().
  2. Do not call join directly from your start() function.
  3. In your join() function, be sure to mark the thread as having been joined/destroyed.
  4. In your destructor, if your thread has not been joined, then you should detach it.

I should also point out that boost::thread provides cross-platform multithreading for C++.

Michael Aaron Safyan