线程互斥
現在想讓線程一個一個執行,那么就要用到線程間互斥:
1 #include <stdio.h> 2 #include <pthread.h> 3 #include <unistd.h> 4 5 pthread_mutex_t mutex; //線程互斥鎖 6 7 void init() 8 { 9 pthread_mutex_init(&mutex ,NULL)//初始化線程互斥鎖 10 } 11 12 void printer(char *str) 13 { 14 pthread_mutex_lock(&mutex);//將該函數鎖住,不允許其他線程調用 15 while(*str != '\0') 16 { 17 putchar(*str); 18 fflush(stdout); 19 str ++; 20 sleep(1); 21 } 22 pthread_mutex_unlock(&mutex);//函數解鎖,允許其他線程調用該函數 23 } 24 25 void *thread_fun_1(void *arg) 26 { 27 char *str = "lan"; 28 printer(str); 29 } 30 31 void *thread_fun_2(void *arg) 32 { 33 char *str = "shanxiao"; 34 printer(str); 35 } 36 37 int main() 38 { 39 init(); 40 41 pthread_t tid1,tid2; 42 43 pthread_create(&tid1, NULL, thread_fun_1, NULL);//創建線程1 44 pthread_create(&tid2, NULL, thread_fun_2, NULL);//創建線程2 45 46 pthread_join(tid1, NULL);//執行線程1 47 pthread_join(tid2, NULL);//執行線程2 48 49 return 0; 50 }pthread_create() 可查看此網頁:http://baike.baidu.com/item/pthread_create?fr=aladdin
pthread_join() 可查看此網頁:http://baike.baidu.com/item/pthread_join?sefr=cr
pthread_mutex_lock()和pthread_mutex_unlock()百度查看。
上面的代碼在Linux系統下的編譯器執行,命令為:gcc 文件名.c -lpthread -o 文件名。比如:gcc printer.c -lpthread -o printer。
Windows系統下沒有試過命令行編譯,有興趣的朋友可以試一試,知道怎樣做的朋友可以在評論區中回復我,謝謝!
轉載于:https://www.cnblogs.com/lanshanxiao/p/6669350.html
總結
- 上一篇: 藤王阁序 王勃
- 下一篇: crontab 提示 command n