两个线程,一个线程打印A,一个线程打印B,如何实现两个线程按顺序打印出ABABAB

方法一:信号量
类似于生产者和消费者问题

#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
sem_t blank_number, product_number;
 
void *producer(void *arg)
{
    while (1) {
        sem_wait(&blank_number);//给blank_number信号量减1,如果blank_number为0,在这里阻塞,直到blank_number不为0
        printf("%c\n",65);
        sem_post(&product_number);//给product_number加1
        sleep(rand()%5);
    }
}
void *consumer(void *arg)
{
    while (1) {
        sem_wait(&product_number);
        printf("%c\n",66);
        sem_post(&blank_number);
        sleep(rand()%5);
}
}
int main(int argc, char *argv[])
{
    pthread_t pid, cid;
    sem_init(&blank_number, 0, 1);//对信号量进行初始化
    sem_init(&product_number, 0, 0);
    pthread_create(&pid, NULL, producer, NULL);
    pthread_create(&cid, NULL, consumer, NULL);
    pthread_join(pid, NULL);//回收线程,当然这块两个线程由于一直在while循环,线程会一直阻塞在这句话
    pthread_join(cid, NULL);
    sem_destroy(&blank_number);//销毁信号量
    sem_destroy(&product_number);
    return 0;
}

方法二、互斥量

#include <stdlib.h>
#include <pthread.h>
#include <stdio.h>
#include <semaphore.h>
 
pthread_mutex_t mutex;
int flag=1;//因为是linux下c语言实现的,所以不能写成bool flag=true;因为bool类型是C++新增的类型
void *printA(void *arg)
{
    while (1) {
        pthread_mutex_lock(&mutex);
        if(flag==1)
	        printf("%c\n",65);
        flag=0;
        pthread_mutex_unlock(&mutex);
        sleep(rand()%5);
    }
}
void *printB(void *arg)
{
    while (1) {
        pthread_mutex_lock(&mutex);
        if(flag==0)
        	printf("%c\n",66);
        flag=1;
        pthread_mutex_unlock(&mutex);
        sleep(rand()%5);
    }
}
int main(int argc, char *argv[])
{
    pthread_t aid, bid;
 
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&aid, NULL, printA, NULL);//创建线程
    pthread_create(&bid, NULL, printB, NULL);
    pthread_join(aid, NULL);//回收线程
    pthread_join(bid, NULL);
 
    pthread_mutex_destroy(&mutex);//销毁互斥量
    return 0;


  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值