threads to take sequential turns.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int turn = 1;
int counter = 0;
int t, n;

struct tData {
        int me;
        int next;
};

pthread_mutex_t mutex;
pthread_cond_t cond;

void *tFunc(void *arg)
{
    struct tData *data;
    data = (struct tData *) arg;
    pthread_mutex_lock(&mutex);
    for (int i = 0; i < n; i++)
    {
        while (turn != data->me)
            pthread_cond_wait(&cond, &mutex);
        counter++;
        turn = data->next;
        printf("%d goes (turn %d of %d), %d next\n", data->me, i+1, n, turn);
        pthread_cond_broadcast(&cond);
    }
    pthread_mutex_unlock(&mutex);
}

int main (int argc, char *argv[]) {
    t = atoi(argv[1]);
    n = atoi(argv[2]);
    struct tData td[t + 1];
    pthread_t threads[t + 1];
    int rc;

    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    for (int i = 1; i <= t; i++)
    {
        td[i].me = i;
        if (i == t)
            td[i].next = 1;
        else
            td[i].next = i + 1;

        rc = pthread_create(&threads[i], NULL, tFunc, (void *)&td[i]);
        if (rc)
        {
            printf("Error: Unable to create thread: %d\n", rc);
            exit(-1);
        }
    }
    void *ret;
    for (int i = 1; i <= t; i++)
        pthread_join(threads[i], &ret);
}


I found this program in a forum and it creates 1 to t threads with each thread pointing to the next and the last thread pointing to the first thread and it allows each thread to sequentially take a turn until all threads have taken n turns. That is when the program ends.

My doubt is if we see in void *tFunc(void *arg) function, first thread locks the mutex and then wait there forever till it's turn comes.Lets say if I spwan 1000 threads and they have take 10 turns each sequentially and what if a 550th thread locks the mutex as soon as the program starts and waiting for its turn which will never happen because still (turn=1) which means it's first thread's turn and first 549 threads have to complete their 1st turn before this 550 threda's turn comes.Doesnt this result in deadlock?

Please help me out.Probably I have got my basics wrong..This problem is eating me out.
The pthread_cond_wait function will automatically release the mutex while waiting.
My doubt is if we see in void *tFunc(void *arg) function, first thread locks the mutex and then wait there forever till it's turn comes.
...
Please help me out.Probably I have got my basics wrong..This problem is eating me out.

The part you're missing is that the thread code runs concurrently.

So, yes; when the first thread is created, it waits for the signal. But while it's waiting, other threads are created and do their thing while in parallel.
Topic archived. No new replies allowed.