Linux 實現用訊號量控制多執行緒操作例項

2021-09-24 05:06:07 字數 688 閱讀 4665

1.有三個執行緒執行以下的程式,執行緒1負責輸入10個整數,判斷整數的奇偶性,如果是偶數執行緒2輸出,如果是奇數執行緒3輸出,執行緒2和執行緒3最後統計輸出偶數和奇數的總數。用訊號量機制實現這三個執行緒的同步與互斥活動,並執行緒來實現。

首先建立出3個執行緒,因為執行緒1必須等執行緒2或執行緒3輸出乙個數才能進行操作,所以需要乙個訊號量,為了控制線程2和執行緒3各自控制自己的部分,所以它們各自也需要1個訊號量,所以一共是三個訊號量。之後就是控制實現pv操作。

#include #include #include #include #define maxsize 10

sem_t s1,s2,s3;

int size=0;

int oddsize=0,evensize=0;

int endflag=0;

void producter()

else

sleep(1);

} endflag=1;

sem_post(&s2);

sem_post(&s3);

}void oddput()

printf("oddsize = %d\n",oddsize);

}void evenput()

printf("evensize = %d\n",evensize);

}int main()

Linux系統訊號量控制

include include include include include include using namespace std const int times 5 const int delay 5 union semaphore static int semaphoreid 0 stati...

訊號量控制併發數

建立乙個訊號量,設定最大併發數為5,5個執行緒,非同步執行 dispatch semaphore tsema dispatch semaphore create 5 dispatch semaphore wait sema,dispatch time forever dispatch async d...

0716Semaphore 訊號量控制程序同步

from multiprocessing import process current process semaphore def funca args args 引數是例項化的semaphoer 開啟乙個檔案,寫入內容,在本函式執行的時候其他程序不能執行 semaphoer例項的acquire 方...