题目:
有三个线程分别打印字符A、B和C,要求按照ABC这样的顺序一直打印字符,形成ABCABCABC........
需要使用信号量进行处理,源代码如下
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <string.h>
#include <stdlib.h>
void* pt1(void* arg);
void* pt2(void* arg);
void* pt3(void* arg);
sem_t s[3];
int main() {
sem_init(&s[0], 0, 1);
sem_init(&s[1], 0, 0);
sem_init(&s[2], 0, 0);
pthread_t pid[3];
pthread_create(&pid[0], NULL, pt1, NULL);
pthread_create(&pid[1], NULL, pt2, NULL);
pthread_create(&pid[2], NULL, pt3, NULL);
int i;
for(i=0; i<3; i++)
pthread_join(pid[i], NULL);
return 0;
}
void* pt1(void* arg) {
while(1) {
sleep(1);
sem_wait(&s[0]);
printf("A");
fflush(stdout);
sem_post(&s[1]);
}
}
void* pt2(void* arg) {
while(1) {
sleep(1);
sem_wait(&s[1]);
printf("B");
fflush(stdout);
sem_post(&s[2]);
}
}
void* pt3(void* arg) {
while(1) {
sleep(1);
sem_wait(&s[2]);
printf("C");
fflush(stdout);
sem_post(&s[0]);
}
}