多线程的顺序执行(信号量,POXIS标准)

c++ 11 提供了基础的 多线程同步语句,也就是: 互斥锁,条件变量,异步,原子锁

信号量机制是LInux POXIS 中的标准的。这个需要注意。

方法1(c),信号量

这个是.c文件,如果是.cpp,因为类型转换更加严格,所以需要改一下。

//使用信号量实现多线程的顺序执行
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

sem_t sem_a, sem_b, sem_c;

void *fun_a() {
    while (1) {
        sem_wait(&sem_a);
        printf("A");
        sem_post(&sem_b);
    }
}

void *fun_b() {
    while (1) {
        sem_wait(&sem_b);
        printf("B");
        sem_post(&sem_c);
    }
}

void *fun_c() {
    while (1) {
        sem_wait(&sem_c);
        printf("C\n");
        sem_post(&sem_a);
    }
}


int main() {
    sem_init(&sem_a, 0, 1);
    sem_init(&sem_b, 0, 0);
    sem_init(&sem_c, 0, 0);

    pthread_t thread_a, thread_b, thread_c;

    pthread_create(&thread_a, NULL, fun_a, NULL);
    pthread_create(&thread_b, NULL, fun_b, NULL);
    pthread_create(&thread_c, NULL, fun_c, NULL);

    while (1);
    return 0;
}

方法1(cpp)

//使用信号量实现多线程的顺序执行
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

sem_t sem_a, sem_b, sem_c;

static void *fun_a(void*) {
    while (1) {
        sem_wait(&sem_a);
        printf("A");
        sem_post(&sem_b);
    }
}

static void *fun_b(void*) {
    while (1) {
        sem_wait(&sem_b);
        printf("B");
        sem_post(&sem_c);
    }
}

static void *fun_c(void*) {
    while (1) {
        sem_wait(&sem_c);
        printf("C\n");
        sem_post(&sem_a);
    }
}


int main() {
    sem_init(&sem_a, 0, 1);
    sem_init(&sem_b, 0, 0);
    sem_init(&sem_c, 0, 0);

    pthread_t thread_a, thread_b, thread_c;

    pthread_create(&thread_a, NULL, fun_a, NULL);
    pthread_create(&thread_b, NULL, fun_b, NULL);
    pthread_create(&thread_c, NULL, fun_c, NULL);

    while (1);
    return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值