How can I execute 3 threads in this order?

74 views Asked by At

I got a problem. I've tried for several days to execute 3 threads in this order in C: Thread 1 Thread 3 Thread 1 Thread 2 Thread 1

I use condition variables. This is my code, and just print:

Thread 1 Thread 3

And it stays blocked

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct node{
int val;
};

void * function(void *);
int turn = 1,var = 3;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t  cond  = PTHREAD_COND_INITIALIZER;


int main(){

int i;
pthread_t *pidthreads = NULL;

struct node *data;


pidthreads = (pthread_t *) calloc(3, sizeof(pthread_t));
pthread_mutex_lock(&mutex);
for(i=1; i<=3; i++){
    data = (struct node*)malloc(sizeof(struct node));
    data->val = i;
    pthread_create(&pidthreads[i], NULL, function, (void*)data);
    printf("Thread [%u] has been created\n", (unsigned int)pidthreads[i]);
    }
    pthread_mutex_unlock(&mutex);

    for(i=1; i<=3; i++)
    pthread_join(pidthreads[i], NULL);

return 0;
}

void * function( void *arg){
int myturn = ((struct node *)arg)->val;

pthread_mutex_lock(&mutex);
while(turn != myturn) pthread_cond_wait(&cond, &mutex);

printf("Thread %d\t[%u]\n", myturn, (unsigned int)pthread_self());

if(turn == 1){
    turn=var;
    var--;
}else{
    if(turn == 3){
        turn = 1;
    }else{
        if(turn == 2){
            turn = 1;
        }
    }
}

pthread_cond_broadcast(&cond);
pthread_mutex_unlock(&mutex);

}

I don't really know how to do this. I appreciate any help.

1

There are 1 answers

1
Wei-Yuan Chen On BEST ANSWER

Add a loop in your function like this.

int myturn = ((struct node *)arg)->val;

while(true){ // add loop

    pthread_mutex_lock(&mutex);
    while(turn != myturn) pthread_cond_wait(&cond, &mutex);
    ....
    pthread_cond_broadcast(&cond);
    pthread_mutex_unlock(&mutex);
}

But you have to add the conditions to leave.

while(true){

    pthread_mutex_lock(&mutex);
    // conditions to leave the waitting loop
    while(turn != myturn && turn!=0) pthread_cond_wait(&cond, &mutex);

    if(turn==0) { // conditions to leave the infinite loop
        pthread_mutex_unlock(&mutex);
        break;
    }
    printf("Thread %d\t[%u]\n", myturn, (unsigned int)pthread_self());
    ...
    pthread_mutex_unlock(&mutex);
}