线程的helloworld

本文展示了一个使用C语言和POSIX线程库实现的简单多线程程序。该程序通过三个线程按顺序打印“apple”、“banana”和“cherry”,展示了线程之间的同步与调度。

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>

pthread_t appId,bnaId,cryId;
int ret;
int status=1;

void apple(){
while (1){
if (status==1){
status=2;
printf("apple\n");
}
pthread_yield(bnaId,NULL);
}
}
void banana(){
while (1){
if (status==2){
status=3;
printf("banana\n");
}
pthread_yield(cryId,NULL);
}
}
void cherry(){
while (1){
if (status==3){
status=1;
printf("cherry\n");
}
pthread_yield(appId,NULL);
}
}
int main(){
ret=pthread_create(&appId,NULL,(void*)apple,NULL);
if (ret!=0){
printf("Creat Apple pthread error!\n");
exit(1);
}
ret=pthread_create(&bnaId,NULL,(void*)banana,NULL);
if (ret!=0){
printf("Creat Banana pthread error!\n");
exit(1);
}
ret=pthread_create(&cryId,NULL,(void*)cherry,NULL);
if (ret!=0){
printf("Creat Cherry pthread error!\n");
exit(1);
}
pthread_join(appId,NULL);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值