种族条件C线程

时间:2016-03-28 12:49:43

标签: c pthreads semaphore race-condition

因此两个线程应该调用两个runTimes函数,runTimes函数应该调用increase_countdecrease_count。最后结果应该是3.问题是当我运行程序时,最后一行代码没有被执行,我无法确定导致竞争条件的原因。

#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 :(得分: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);