如何讓兩個執行緒交替列印整數1-100?你的答案呢?
阿新 • • 發佈:2018-11-11
前端時間下班臨走前看到同事做嘗試的一個題目:如何讓兩個執行緒交替列印整數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++選手的思路截然不同^_^