linux两个线程交替执行,如何让两个线程交替打印整数1-100?你的答案呢?

分享一位C++程序员的趣事,他在重温编程乐趣时,展示了如何使用线程优先级控制让两个线程交替打印1-100,展示了不同的编程思维策略。同时回顾了利用__sync_fetch_and_add操作原子增减索引的方法。
摘要由CSDN通过智能技术生成

前端时间下班临走前看到同事做尝试的一个题目:如何让两个线程交替打印整数1-100?

好几年没有写代码玩了,想了想,花了十多分钟写了个答案:

#include

#include

#include

#include

#include

#include

#include

#include

#include

static int index=1;

void* t1(void* context) {

while(index < 100) {

if (index & 0x1L) {

printf("t1 %d\n", index);

__sync_fetch_and_add(&index, 1);

} else {

usleep(0);

}

}

}

void* t2(void* context) {

while(index < 100) {

if (!(index & 0x1L)) {

printf("t2 %d\n", index);

__sync_fetch_and_add(&index, 1);

} else {

usleep(0);

}

}

}

int main() {

pthread_t tid1, tid2 ;

pthread_create(&tid1, NULL,t1,NULL);

pthread_create(&tid2, NULL,t2,NULL);

pthread_join(tid1,NULL);

pthread_join(tid2,NULL);

return 0;

}

晚上回家想了想,第二天又写了个答案,利用Linux的线程优先级0-99,通过控制线程优先级来保证打印顺序,代码找不到了,这里不帖了。同事是JAVA玩家,跟我这老派C/C++选手的思路截然不同^_^

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值