我一直在試圖學習這個簡單的門票銷售計劃的信號量。唯一的問題是當前的信號量不能保護numTickets
和ticketsSold
的值。我發現這是因爲有時賣出的總票數加起來最多爲51.C信號量沒有按預期鎖定
是否正確執行信號量?
#include <semaphore.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
int numTickets;
sem_t mySem;
void* sell_ticket(void *sellerNum) {
int sell = (int) sellerNum;
int ticketsSold = 0;
while (numTickets > 0) {
srand (time(NULL));
int random_number = rand();
for (int i = 1; i < random_number % 5 ; i++) {
if (numTickets > 0) {
sem_wait(&mySem);
numTickets--;
ticketsSold++;
printf("Seller # %d sold a ticket. Tickets left: %d\n", sell, numTickets);
sem_post(&mySem);
}
}
}
printf("Seller #%d noticed all tickets sold! (I sold %d myself) \n", sell, ticketsSold);
}
int main() {
numTickets = 50;
int numSellers = 4;
sem_init(&mySem, 0, 1);
pthread_t sellerThread;
for (int i = 0; i < numSellers; i++) {
pthread_create(&sellerThread, NULL, sell_ticket, (void *)i);
}
for (int i = 0; i < numSellers; i++) {
pthread_join(sellerThread, NULL);
}
printf("All tickets sold!\n");
return 0;
}
我毫不客氣的並行線程的專家,但預計在讀numTickets(在'if'和'while')時,另一個線程正在寫這是問題。您需要在受信號量保護的塊內獲得讀取 - 修改 - 寫入序列。 – Gene
我已經嘗試了上面的建議。不幸的是,經過各種測試,我得到了51的值。 –