Hi
I am trying to print repeated pattern using thread only 5 times when number of thread are 5 but my program is not coming out of the thread,and waiting for somewhere ,giving me wrong output
wrong output:-
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t *cond = NULL;
int threads;
staticint cnt = 0;
int MAX_CYCLE = 1; // Changed to 1 for debugging
staticint CYCL_CNT = 0;
// function to synchronize threads
void *foo(void *arg)
{ // turn is basically to identify a thread
int turn = *(int *) arg;
while (CYCL_CNT < MAX_CYCLE) {
pthread_mutex_lock(&mutex);
if (turn != cnt) {
pthread_cond_wait(&cond[turn], &mutex);
}
printf("%d ", turn + 1);
if (cnt < threads - 1) {
cnt++;
} else {
cnt = 0;
CYCL_CNT++;
printf("\n");
}
// weak up next thread
pthread_cond_signal(&cond[cnt]);
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main()
{
pthread_t *tid;
volatileint i;
int *arr;
printf("\nEnter number of threads: ");
scanf("%d", &threads);
// allocate memory to cond (conditional variable),
// thread id's and array of size threads
cond = (pthread_cond_t *) malloc(sizeof(pthread_cond_t) * threads);
tid = (pthread_t *) malloc(sizeof(pthread_t) * threads);
arr = (int *) malloc(sizeof(int) * threads);
// create threads
for (i = 0; i < threads; i++) {
arr[i] = i;
pthread_create(&tid[i], NULL, foo, (void *) &arr[i]);
}
// waiting for thread
for (i = 0; i < threads; i++) {
pthread_join(tid[i], NULL);
}
return 0;
}
I've identified the following issues.
1. It's unnecessary (and perhaps dangerous) to cast the return result of malloc in a C program. If you've included stdlib.h, you're good to go. If you haven't included stdlib.h, the cast serves only to hide the fact that the implicit int malloc(); declaration the compiler invents is broken.
2. You don't call pthread_cond_init() on any of the condition variables you create.
3. You get the "almost one extra row" because all but the last thread go round one more time because while (CYCL_CNT < MAX_CYCLE) is still true, and it's only the last thread which has CYCL_CNT++; that makes it (alone) do the right thing.
thanks for the comments, but still I am not getting how to improve (CYCL_CNT < MAX_CYCLE)
condition, can you please bring the necessary correction and paste here.
thanks in advance.
You make CYCL_CNT = MAX_CYCLE only at last row and last column. But all threads (except last one) check while(…) before it happens. So they are ready & do for for one more turn.