Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

multi thread launch arrangement

I have 2 thread to create thread1 and thread2. When creating threads with:

pthread_create(&thread1, NULL, &function_th1, NULL);
pthread_create(&thread2, NULL, &function_th2, NULL);

The thread2 is launched before the thread1 and I'm looking for a solution to start thread1 before thread2.

Not looking for this solution:

pthread_create(&thread2, NULL, &function_th2, NULL);
pthread_create(&thread1, NULL, &function_th1, NULL);
like image 985
developer Avatar asked May 05 '26 22:05

developer


2 Answers

There is no relation between when a thread creation call is issued and when the thread actually starts executing. It all depends on implementation, OS, etc. that's why you are seeing the two threads actually starting in a seemingly random order.

If you need thread 1 to start before thread 2 you probably have some data/logical dependency on some event. In this case you should use a condition variable to tell thread 2 when to actually begin executing.

// condition variable
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
// associated mutex
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// state for condition variable
int shouldWait = 1;

...

void* function_th1(void* p) {
     // execute something

     // signal thread 2 to proceed
     pthread_mutex_lock(&mutex);
     shouldWait = 0;
     pthread_cond_signal(&cond);
     pthread_mutex_unlock(&mutex);

     // other stuff
}

void* function_th2(void* p) {
     // wait for signal from thread 1
     pthread_mutex_lock(&mutex);
     while(shouldWait) {
         pthread_cond_wait(&cond, &mutex);
     }
     pthread_mutex_unlock(&mutex);

     // other stuff
}    
like image 100
Tudor Avatar answered May 08 '26 13:05

Tudor


Move the 'pthread_create(&thread2, NULL, &function_th2, NULL);' to the top of the 'function_th1' function.

That will certainly achieve what you ask for, no complex signalling required.

Whether what you ask for is what you actually want or need is another matter.

like image 32
Martin James Avatar answered May 08 '26 13:05

Martin James