使用C語言中的執行緒同步順序列印數字。
給定執行緒,程式必須根據從0到10的優先順序列印執行緒。
什麼是執行緒?
執行緒是在程式內執行的輕量級程序。一個簡單的程式可以包含n個執行緒。
與Java不同,多執行緒不受語言標準的支援,POSIX執行緒(Pthreads)是C/C++中多執行緒使用的標準。C語言本身並不包含對多執行緒應用程式的任何內建支援,而是完全依賴作業系統提供此功能。
它在我們的程式中是如何工作的?
要使用執行緒函式,我們使用標頭檔案#include <pthread.h>。此標頭檔案將包含程式中與執行緒相關的全部函式,例如pthread_create()等。
現在的任務是使用gcc編譯器提供的pthread標準庫來同步n個執行緒。其思想是獲取執行緒數,並在第一個執行緒中列印1,在第二個執行緒中列印2,在第三個執行緒中列印3,直到第十個執行緒。輸出將根據執行緒的優先順序包含1到10的數字。
演算法
Start Step 1 -> Declare global variables as int MAX=10 and count=1 Step 2 -> declare variable thr of pthread_mutex_t and cond of pthread_cond_t Step 3 -> Declare Function void *even(void *arg) Loop While(count < MAX) Call pthread_mutex_lock(&thr) Loop While(count % 2 != 0) Call pthread_cond_wait(&cond, &thr) End Print count++ Call pthread_mutex_unlock(&thr) Call pthread_cond_signal(&cond) End Call pthread_exit(0) Step 4 -> Declare Function void *odd(void *arg) Loop While(count < MAX) Call pthread_mutex_lock(&thr) Loop While(count % 2 != 1) Call pthread_cond_wait(&cond, &thr) End Print count++ Call pthread_mutex_unlock(&thr) Call pthread_cond_signal(&cond) End Set pthread_exit(0) Step 5 -> In main() Create pthread_t thread1 and pthread_t thread2 Call pthread_mutex_init(&thr, 0) Call pthread_cond_init(&cond, 0) Call pthread_create(&thread1, 0, &even, NULL) Call pthread_create(&thread2, 0, &odd, NULL) Call pthread_join(thread1, 0) Call pthread_join(thread2, 0) Call pthread_mutex_destroy(&thr) Call pthread_cond_destroy(&cond) Stop
示例
#include <pthread.h> #include <stdio.h> #include <stdlib.h> int MAX = 10; int count = 1; pthread_mutex_t thr; pthread_cond_t cond; void *even(void *arg){ while(count < MAX) { pthread_mutex_lock(&thr); while(count % 2 != 0) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0); } void *odd(void *arg){ while(count < MAX) { pthread_mutex_lock(&thr); while(count % 2 != 1) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0); } int main(){ pthread_t thread1; pthread_t thread2; pthread_mutex_init(&thr, 0); pthread_cond_init(&cond, 0); pthread_create(&thread1, 0, &even, NULL); pthread_create(&thread2, 0, &odd, NULL); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&thr); pthread_cond_destroy(&cond); return 0; }
輸出
如果我們執行上面的程式,它將生成以下輸出
1 2 3 4 5 6 7 8 9 10
廣告