I created 5 threads in the program and assign ID 1,2,3,4,5 to them respectively. Each thread will try to access the Next_ID. When a thread acquires Next_ID it compares its ID with the Next_ID. If it matches I print my turn and others print not my turn. And increments Next_ID by 1. If Next_ID reaches 6 it resets back to 1. However my code prints the following:
My Turn: 1
Not My Turn: 3
My Turn: 4
My Turn: 5
Not My Turn: 2
Not My Turn: 1
Not My Turn: 3
My Turn: 4
My Turn: 5
Not My Turn: 2
Not My Turn: 1
Not My Turn: 3
My Turn: 4
My Turn: 5
Not My Turn: 2
Not My Turn: 1
Not My Turn: 3
My Turn: 4
My Turn: 5
Not My Turn: 2
Not My Turn: 1
Not My Turn: 3
My Turn: 4
My Turn: 5
The expected output should be:
My Turn: 1
not my Turn: 2
not my Turn: 3
not my Turn: 4
not my Turn: 5
not my Turn: 1
My Turn: 2
not my Turn: 3
not my Turn: 4
not my Turn: 5
My code:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 5
int Next_ID = 1;
pthread_t threads[NUM_THREADS];
pthread_mutex_t mutex;
typedef struct threadArgs {
int threadId;
int numOfCalls;
} ThreadArgs;
ThreadArgs threadArgsArray[NUM_THREADS];
void * printThread(void *pThreadArgs) {
ThreadArgs *threadArgs = (ThreadArgs *) pThreadArgs;
int *threadId = &threadArgs->threadId;
for(int i = 0; i < 20; i++) {
pthread_mutex_lock(&mutex);
if (Next_ID == *threadID) {
printf("My Turn: %d\n", *threadId);
} else {
printf("Not My Turn: %d\n", *threadId);
}
Next_ID = (*threadId == 5) ? 1 : *threadId + 1;
pthread_mutex_unlock (&mutex);
}
pthread_exit(NULL);
}
void * printThread(void *);
int main(int argc, char const *argv[]) {
pthread_attr_t attr;
void *status;
pthread_mutex_init(&mutex, NULL);
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
for (int i = 0; i < NUM_THREADS; i++) {
threadArgsArray[i].threadId = i + 1;
int rc = pthread_create(&threads[i], &attr, printThread,
&threadArgsArray[i]);
}
for (int i = 0; i < NUM_THREADS; i++) {
int rc = pthread_join(threads[i], &status);
}
pthread_attr_destroy(&attr);
pthread_mutex_destroy(&mutex);
pthread_exit(NULL);
}