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.
Add a loop in your function like this.
But you have to add the conditions to leave.