交替打印ABC(C)

本文介绍如何使用信号量semaphore实现线程同步,通过三个子线程printA、printB和printC按照ABC顺序交替执行,展示了如何使用`sem_wait`和`sem_post`进行线程间的协作。
摘要由CSDN通过智能技术生成
交替打印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;
}   
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值