As described in title:
Write a program to open 3 threads, the IDs of the 3 threads are A, B,C, each thread prints its own ID on the screen 10 times, requiring the output to be displayed in the order of ABC, such as: abcabc ... . Recursion in turn.
With Pthread_cond_signal, the thread that was supposed to get the signal in theory would have been starving, but I tried it, and every run was OK.
#include <stdio.h>#include<stdlib.h>#include<string.h>#include<pthread.h>#include<errno.h>pthread_cond_t cond_a;pthread_mutex_t Mylock;intG_flag;#defineNUM 3void* Func (void*Arg) { inti; intName = (int) Arg; printf ("my name [%d]\n", name); for(i =0; i<Ten; i++) { if(Pthread_mutex_lock (&Mylock)) {printf ("Pthread_mutex_lock Error errmsg[%s]\n", Strerror (errno)); Exit (0); } while(1) { if(G_flag = =name) {G_flag= (g_flag+1)%NUM; printf ("%c",'A'+name); Break; } Else { if(Pthread_cond_wait (&cond_a, &Mylock)) {printf ("Wait Error errmsg[%s]\n", Strerror (errno)); Exit (0); } } } if(Pthread_mutex_unlock (&Mylock)) {printf ("Pthread_mutex_unlock Error errmsg[%s]\n", Strerror (errno)); Exit (0); } //if (Pthread_cond_broadcast (&cond_a)) if(Pthread_cond_signal (&cond_a)) {printf ("pthread_cond_broadcast Error errmsg[%s]\n", Strerror (errno)); Exit (0); }} printf ("\ n"); Pthread_exit (NULL);}intAppinit () {G_flag=0; Pthread_mutex_init (&Mylock, NULL); Pthread_cond_init (&cond_a, NULL); return 0; }intAppdone () {Pthread_cond_destroy (&cond_a); Pthread_mutex_destroy (&Mylock); return 0;}intMainintargcChar*argv[]) {pthread_t Th[num]; intret; inti; RET=Appinit (); if(ret) {printf ("Appinit failure\n"); return-1; } for(i =0; i < NUM; i++) {ret= Pthread_create (&th[i], NULL, Func, (void*) (i); if(ret) {printf ("pthread_create ta error [%s]\n", Strerror (errno)); return 1; } } for(i =0; i < NUM; i++) Pthread_join (Th[i], NULL); printf ("Main thread exit\n"); RET=Appdone (); if(ret) {printf ("Appdone failure\n"); return-1; } return 0;}
View Code
Join me in a face exam-linux threading Programming (3)