#include <stdio.h>#include<pthread.h>#include<unistd.h>#include<iostream>using namespacestd;pthread_t thread[2];//thread function return valuepthread_mutex_t Mut;//Mutual exclusion LockintCnt=0;void*thread1 (void*args) {cout<<"T1 start!"<<Endl; for(inti =0; I <Ten; i++) {Pthread_mutex_lock (&mut);//lock, protect shared resourcescnt++; Pthread_mutex_unlock (&mut);//UnlockSleep1); } cout<<"T1 wait!"<<Endl; Pthread_exit (NULL);}void*thread2 (void*args) {cout<<"T2 start!"<<Endl; for(inti =0; I <Ten; i++) {Pthread_mutex_lock (&mut);//lock, protect shared resourcescnt++; Pthread_mutex_unlock (&mut);//UnlockSleep1); } cout<<"T2 wait!"<<Endl; Pthread_exit (NULL);}voidThread_create (void) {pthread_create (&thread[0], NULL, THREAD1, NULL); cout<<"T1 create!"<<Endl; Pthread_create (&thread[1], NULL, THREAD2, NULL); cout<<"T2 create!"<<Endl;}voidThread_wait (void) {Pthread_join (thread[0],null); cout<<"T1 done!"<<Endl; Pthread_join (thread[1],null); cout<<"T1 done!"<<Endl;}intMain () {Pthread_mutex_init (&mut,null); Thread_create (); Thread_wait (); return 0;}
C Implementing multithreading