线程顺序执行(phtread)

本文展示了一个使用C++和线程同步技术实现的程序,该程序创建了三个线程,分别打印字符A、B、C,确保输出结果按照ABC顺序呈现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC.依次递推。


程序代码如下:

#include<iostream>
#include<cstdlib>
using namespace std;


#ifdef __cplusplus
extern "C"
{
#endif


#include<pthread.h>
#include<semaphore.h>
#ifdef __cplusplus
}
#endif


sem_t sem1,sem2,sem3;
int var = 1;
void *PrintA(void *ptr)
{
    int i;
    for(i = 0; i < 10; i++)
    {
         sem_wait(&sem1);
         cout<<"A";
         sem_post(&sem2);
   } 
   return NULL;
}
void *PrintB(void *ptr)
{
    for(int i = 0; i < 10; i++)
    {
         
         sem_wait(&sem2);
         cout<<"B";
         sem_post(&sem3);
    }
    return NULL;
}
void *PrintC(void *ptr)
{
    for(int i = 0; i < 10; i++)
    {
         sem_wait(&sem3);
         cout<<"C";
         sem_post(&sem1);
    }
    return NULL;
}




void init_thread()
{
   int rc1,rc2,rc3;
   pthread_t thread1,thread2,thread3;
   sem_init(&sem1,0,0);
   sem_init(&sem2,0,0);
   sem_init(&sem3,0,0);
   
   if( (rc1 = pthread_create(&thread1,NULL,PrintA,NULL) ))
   {
       cout<<"create thread is failed"<<endl;
       exit(1);
   }
   
   if( (rc2 = pthread_create(&thread2,NULL,PrintB,NULL) ))
   {
       cout<<"create thread is failed"<<endl;
       exit(1);
   }
   
   if( (rc3 = pthread_create(&thread3,NULL,PrintC,NULL) ))
   {
       cout<<"create thread is failed"<<endl;
       exit(1);
   }
   sem_post(&sem1);
   pthread_join(thread1,NULL);
   pthread_join(thread2,NULL);
   pthread_join(thread3,NULL);
}
int main(int argc,char *argv[])
{
   init_thread();
   cout<<endl;   
   return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值