Reputation: 225
#include<stdio.h>
#include<pthread.h>
#define nThreads 5
pthread_mutex_t lock;
void *start(void *param) {
pthread_mutex_lock(&lock);
while (true)
{
//do certain things , mutex to avoid critical section problem
int * number = (int *) param;
cout<<*number;
}
pthread_mutex_unlock(&lock);
}
int main()
{
pthread_mutex_init(&lock, NULL);
pthread_t tid[nThreads];
int i = 0;
for(i = 0; i < nThreads; i++) pthread_create(&tid[i], NULL, start, (void *) &i);
for(i = 0; i < nThreads; i++) pthread_join(tid[i], NULL);
pthread_mutex_destroy(&lock);
return 0;
}
my question is whether all the threads are looping infinitely or only the first thread is looping. and if only one thread is looping, how to make all threads loop infinitely and should mutex be inside the while loop or outside :S !!
thanks in advance.
Upvotes: 0
Views: 938
Reputation: 680
In this case only 1 thread is in loop , also this will be the first thread to enter since that will never unlock mutex no other thread will enter ie, all other thread will wait indefinitely. I think what you want is this:
while (true)
{
pthread_mutex_lock(&lock);
//do certain things , mutex to avoid critical section problem
int * number = (int *) param;
cout<<*number;
pthread_mutex_unlock(&lock);
}
Upvotes: 0
Reputation: 17936
If the mutex is outside the loop as you've shown, then only one thread can enter that loop. If that loop runs forever (as while (true)
will do if there's no break
statement inside), then only one thread will actually get to loop and the rest will be locked out.
Move the mutex around just the code that you need to protect. If you want all the threads looping in parallel, taking turns accessing a common structure, move the mutex inside the loop.
Upvotes: 2