I am trying to print i th letter of english by i th thread where i is a natural number one by one in the following program. I want to print A B C D E F... by the thread 1 2 3 4.... How to print the letters A B C D E F by using mutex lock in the following thread program?
Code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
pthread_mutex_t mutex;
int i1=0;
int m[]={0,1,2,3,4,5};
void *text(void *arg)
{
int *n = (int *)arg;
if((*n)==i1){
pthread_mutex_lock(&mutex);
i1++;
switch ((*n))
{
case 0:
printf("A ");
break;
case 1:
printf("B ");
break;
case 2:
printf("C ");
break;
case 3:
printf("D ");
break;
case 4:
printf("E ");
break;
case 5:
printf("F ");
break;
}
pthread_mutex_unlock(&mutex);
}
pthread_exit(0);
}
int main()
{
int i;
if(pthread_mutex_init(&mutex, NULL)!=0) {printf("mutex initialisation has failed"); return 1;}
pthread_t tid[6];
for (i=0;i<6;i++)
{
if(pthread_create(&tid[i],NULL,text,(void *)&m[i])!=0) {printf("Thread creation has failed");return 1;}
}
for (i=0;i<6;i++) pthread_join(tid[i], NULL);
pthread_mutex_destroy(&mutex);
return 0;
}