Linux多线程编程 使用sem实现同步互斥
创建3个线程,其中tid分别为A,B,C,每个线程都把自己的tid打印到屏幕,循环10次,但顺序必须是“ABCABCABC…“
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
sem_t semA,semB,semC;
int twice=0;
void *pthreadA(void *arg){
int i;
printf("tid A %ld\n",pthread_self());
for(i=0;i<10;i++){
sem_wait(&semA);
twice++;
sleep(1);
printf("A \n");
sem_post(&semB);
}
}
void *pthreadB(void *arg){
int i;
printf("tid b %ld\n",pthread_self());
for(i=0;i<10;i++){
sem_wait(&semB);
twice++;
sleep(1);
printf("B \n");
sem_post(&semC);
}
}
void *pthreadC(void *arg){
int i;
printf("tid c %ld\n",pthread_self());
for(i=0;i<10;i++){
sem_wait(&semC);
twice++;
sleep(1);
printf("C \n");
sem_post(&semA);
}
}
void main(){
int i;
printf("the main pth start\n");
pthread_t apth,bpth,cpth;
sem_init(&semA,0,1);
sem_init(&semB,0,0);
sem_init(&semC,0,0);
pthread_create(&bpth,NULL,pthreadB,NULL);
pthread_create(&apth,NULL,pthreadA,NULL);
pthread_create(&cpth,NULL,pthreadC,NULL);
pthread_join(apth,NULL);
pthread_join(bpth,NULL);
pthread_join(cpth,NULL);
sem_destroy(&semA);
sem_destroy(&semB);
sem_destroy(&semC);
printf("over");
}
运行结果: