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++选手的思路截然不同^_^

  • 相关阅读:
    第一阶段冲刺02
    梦断代码阅读笔记01
    第一阶段冲刺01
    第十周总结报告
    单词统计
    用户模板分析
    第九周总结
    第九周课后作业
    py_11_ 0726
    Day_01
  • 原文地址:https://www.cnblogs.com/dskit/p/9943388.html
Copyright © 2011-2022 走看看