首页 > 解决方案 > 产生竞争条件

问题描述

csfunc我正在尝试使用以下示例代码产生一个竞争条件(假设存在一个关键部分):

#include <stdio.h>
#include <pthread.h>
  
int cs = 0;

void* csfunc(void* arg){

    for (int i = 0; i < 1000000; i++){

        cs++;
        cs--;

        if (cs!=0){
        
            printf("cs: %d\n", cs);
        }
    }
}
  
  
int main(){
    
    for (int i = 0; i < 100; i++){

        pthread_t t;
        pthread_create(&t,NULL,csfunc,NULL);
        pthread_join(t,NULL);
    }
    return 0;
}

我假设 100 个线程和 1000000 次迭代足以完成很多竞争条件。尽管如此,我的代码甚至没有打印出cs. 有任何想法吗?还是我错过了什么?

PS> 请注意,我正在使用gcc带有以下命令的编译器

gcc cs.c -lpthread -o cs

标签: cmultithreadingpthreadsrace-conditioncritical-section

解决方案


当您加入时,它会等到该线程完成然后继续循环。因此,您应该将线程句柄放在一个数组中并等待所有这些句柄。

pthread_t handles[100];
for (int i = 0; i < 100; i++){
    pthread_create(&handles[i],NULL,csfunc,NULL);
}
for (int i = 0; i < 100; ++i)
    pthread_join(handes[i],NULL);

推荐阅读