如何让两个线程交替打印整数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\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++选手的思路截然不同^_^

posted @ 2018-11-11 20:33  dskit  阅读(1186)  评论(0编辑  收藏  举报