c - Serializing POSIX threads using Mutex -


i trying make program creates 3 threads threa1 thread2 , thread3 thread1 prints thread1 5 times, thread2 prints thread2 5 times , thread3 prints thread3 5 times want use mutexes have output

thread1 thread1 thread1 thread1 thread1 thread2 thread2 thread2 thread2 thread2 thread3 thread3 thread3 thread3 thread3 

how can ?

this solution :

#include <stdio.h> #include <stdlib.h> #include <time.h> #include <assert.h> #include <pthread.h>  #define max_print 5 #define max_thread 3  static pthread_mutex_t mthread[max_thread] = {pthread_mutex_initializer, pthread_mutex_initializer, pthread_mutex_initializer};  void * start_thread(void * arg) {     int thnb = *((int*)arg);     int = 0;      pthread_mutex_lock(&mthread[thnb]);      (i = 0; < max_print; i++) {         fprintf(stdout, "thread%d\n", thnb);     }      pthread_mutex_unlock(&mthread[thnb]);      return null; }   int main() {     pthread_t thread[max_thread];     int arg[max_thread];     int = 0;      printf("init mutex threads ...");     (i = 0; < max_thread; i++) {         pthread_mutex_lock(&mthread[i]);     }     printf("ok\n");      printf("creating threads ...");     (i = 0; < max_thread; i++) {         arg[i] = i;         pthread_create(&thread[i], null, &start_thread, &arg[i]);     }     printf("ok\n");      printf("::::::::::::::::: output want :::::::::::::::::::::: \n");     (i = 0; < max_thread; i++)     {         pthread_mutex_unlock(&mthread[i]);         pthread_join(thread[i], null);     }       return 0; } 

compile using:

gcc -d_reentrant -lpthread main.c 

Comments

Popular posts from this blog

c++ - OpenCV Error: Assertion failed <scn == 3 ::scn == 4> in unknown function, -

php - render data via PDO::FETCH_FUNC vs loop -

The canvas has been tainted by cross-origin data in chrome only -