交替打印ABC
使用信号量实现线程同步,分别创建三个子线程,让子线程按照一定的顺序依次执行。
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t ab, bc, ca;
void print(const char c, sem_t *sem1, sem_t *sem2)
{
for (int i = 0; i < 5; i++)
{
sem_wait(sem1);
printf("%d %c\n", pthread_self(), c);
// ++i;
sem_post(sem2);
}
}
void *printA(void *args)
{
print('A', &ab, &bc);
return NULL;
}
void *printB(void *args)
{
print('B', &bc, &ca);
return NULL;
}
void *printC(void *args)
{
print('C', &ca, &ab);
return NULL;
}
int main()
{
sem_init(&ab, 0, 1);
sem_init(&bc, 0, 0);
sem_init(&ca, 0, 0);
int vals[3];
// 获取信号量的值
sem_getvalue(&ab, &vals[0]);
sem_getvalue(&bc, &vals[1]);
sem_getvalue(&ca, &vals[2]);
printf("对应信号量的值为: ");
for (int i = 0; i < 3; i++) {
printf("%d ", vals[i]);
}
printf("\n");
// 创建子线程
pthread_t tids[3];
pthread_create(&tids[0], NULL, printA, NULL);
pthread_create(&tids[1], NULL, printB, NULL);
pthread_create(&tids[2], NULL, printC, NULL);
pthread_join(tids[0], NULL);
pthread_join(tids[1], NULL);
pthread_join(tids[2], NULL);
sem_getvalue(&ab, &vals[0]);
sem_getvalue(&bc, &vals[1]);
sem_getvalue(&ca, &vals[2]);
printf("对应信号量的值为: ");
for (int i = 0; i < 3; i++) {
printf("%d ", vals[i]);
}
sem_destroy(&ab);
sem_destroy(&bc);
sem_destroy(&ca);
}
P(-1)、V(+1)操作
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
sem_t a, b, c;
void* PrintA(void *arg) {
for(int i = 0; i < 5; i++) {
sem_wait(&a);
printf("A\n");
sem_post(&b);
}
return NULL;
}
void* PrintB(void *arg) {
for(int i = 0; i < 5; i++) {
sem_wait(&b);
printf("B\n");
sem_post(&c);
}
return NULL;
}
void* PrintC(void *arg) {
for(int i = 0; i < 5; i++) {
sem_wait(&c);
printf("C\n");
sem_post(&a);
}
return NULL;
}
int main() {
sem_init(&a, 0, 1);
sem_init(&b, 0, 0);
sem_init(&c, 0, 0);
pthread_t thread[3];
pthread_create(&thread[0], NULL, PrintA, NULL);
pthread_create(&thread[1], NULL, PrintB, NULL);
pthread_create(&thread[2], NULL, PrintC, NULL);
for(int i = 0; i < 3; i++) {
pthread_join(thread[i], NULL);
}
sem_destroy(&a);
sem_destroy(&b);
sem_destroy(&c);
return 0;
}