2016-03-28 21 views
-1

İki iş parçacığı iki runTimes işlevini çağırmalı ve runTimes işlevi increase_count ve decrease_count'u çağırmalıdır. Sonuçta sonuç 3 olmalıdır. Sorun, programı çalıştırdığımda kodun son satırının yürütülmemesi ve yarış koşullarına neyin sebep olduğunu gerçekten belirleyemem.Race Condition C iş parçacığı

#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

Kodu doğru girinti Lütfen olmak değiştiririm belirleyin. –

+0

düzeltildi, üzgünüm – Mattia

+0

"* corrected *"? Hala karışıklık görüyorum. – alk

cevap

0

kodunun son satırı

Bu çağırmadan önce

pthread_exit(NULL); 

diyoruz beacuse olduğunu yürütülen almaz bu

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

(son) hat.

pthread_exit() o işlevini çağırır iplik, akım parçacığı çıkar.


Gösterdiğiniz koddaki yarış bununla ilgili değil. Kod, aynı değişkenlere aynı anda erişmeye karşı herhangi bir koruma uygulamadığı için ortaya çıkabilir. Ayrıca, oluşturduğunuz konulara katılmak da istersiniz.

yüzden

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

Neyse, idam edilmeden sonra koyarsam ne yapmalıyım? – Mattia

+1

'pthread_exit (NULL)' den kurtulun; yorum yap, sil, yok et, yok et, onu yok et. –

İlgili konular