2016-03-28 119 views
-1

所以兩個線程應該調用兩個runTimes函數,而runTimes函數應該調用increase_countdecrease_count。最後結果應該是3.問題是,當我運行程序時,最後一行代碼沒有得到執行,我也無法確定是什麼原因導致競爭條件。競爭條件C線程

#define MAX_RESOURCES 5 


int available_resources = MAX_RESOURCES; 
int times = 100000; 
pthread_mutex_t mutex; 
sem_t semaphore; 

/* decrease available_resources by count resources 
* return 0 if sufficient resources available, 
* otherwise return -1 */ 
int decrease_count(int count) { 
if (available_resources < count) { 
    return -1; 
} else { 
    available_resources -= count; 
    printf("Locked %i resources, now available: %i\n" , count , available_resources); 
    return 0; 
} 
} 


/* increase available resources by count */ 
int increase_count(int count) { 
if (count + available_resources > 5) { 
    return -1; 
} else { 
    available_resources += count; 
    printf("Freed %i resources, now available: %i\n" , count , available_resources); 
    return 0; 
} 
} 


void *runTimes(void *null) { 
int i = 0 , result; 
while (i < times) { 
    result = -1; 
    while (result < 0) {result = decrease_count(1);} 
    result = -1; 
    while (result < 0) {result = increase_count(1);} 
    i += 1; 
    printf("Count; %i\n",i); 
} 

return NULL; 
} 

int main(int argc, char *argv[]) 
{ 
pthread_t thread1 , thread0; 
pthread_t threads [2]; 

decrease_count(2); 

pthread_create(&thread0, NULL, runTimes, NULL); 
pthread_create(&thread1, NULL, runTimes, NULL); 

int i = 0; 
while(i < 2) { 
    pthread_join(threads[i], NULL); 
    i++; 
} 

pthread_exit(NULL); 


printf("Currently available resources (should be 3): %i\n" , available_resources); 

return 0; 
} 
+1

請正確縮進代碼。 –

+0

已更正,對不起 – Mattia

+0

「*校正*」?我仍然看到一團糟。 – alk

回答

0

的最後一行代碼沒有得到執行

這是怎麼一回事,因爲你在調用之前調用

pthread_exit(NULL); 

printf("Currently available resources (should be 3): %i\n" , available_resources); 

(最後)線。

pthread_exit()退出當前線程,是調用函數的線程。


您顯示的代碼中的種族與此無關。可能會出現這種情況,因爲代碼沒有實現對同時訪問相同變量的任何保護。


您還想加入您創建的線程。

這樣做改變

pthread_create(&thread0, NULL, runTimes, NULL); 
pthread_create(&thread1, NULL, runTimes, NULL); 

pthread_create(&threads[0], NULL, runTimes, NULL); 
pthread_create(&threads[1], NULL, runTimes, NULL); 
+0

如果我把它放在它沒有被執行後,我該怎麼辦? – Mattia

+1

擺脫'pthread_exit(NULL);'評論它,刪除它,摧毀它,消除它,取而代之。 –