zoukankan      html  css  js  c++  java
  • 如何让两个线程交替打印整数1-100?你的答案呢?

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

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

    #include<stdio.h>
    #include <pthread.h>
    #include <stdlib.h>
    
    #include<stdio.h>
    #include <pthread.h>
    #include <stdlib.h>
    
    #include<stdio.h>
    #include <pthread.h>
    #include <stdlib.h>
    
    static int index=1;
    
    void* t1(void* context) {
        while(index < 100) {
            if (index & 0x1L) {
                printf("t1 %d
    ", index);
               __sync_fetch_and_add(&index, 1);
            } else {
                usleep(0);
            }
        }
    }
    
    void* t2(void* context) {
        while(index < 100) {
            if (!(index & 0x1L)) {
                printf("t2 %d
    ", 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++选手的思路截然不同^_^

  • 相关阅读:
    SpringCloud 学习之概述
    定位慢查询
    中止线程
    笨办法41学会说面向对象【pyinstaller安装使用
    pip安装
    笨办法40模块, 类和对象class
    笨办法39字典dict
    笨办法38列表操作
    笨办法35分支和函数
    笨办法34访问列表元素(列表方法)
  • 原文地址:https://www.cnblogs.com/dskit/p/9943388.html
Copyright © 2011-2022 走看看