c - 产生竞争条件
问题描述
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
解决方案
当您加入时,它会等到该线程完成然后继续循环。因此,您应该将线程句柄放在一个数组中并等待所有这些句柄。
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);
推荐阅读
- android - Android 视觉 - 人脸、眼镜和帽子检测
- python - 我可以绘制一个条形图,其中每个条形的颜色取决于该值是大于还是小于先前值
- javascript - 如果树枝模板包含在父模板 foreach 循环中,则防止 JavaScript 多次加载
- javascript - JavaScript 导致 CSS 转换不起作用
- node.js - 捆绑 Node.js 应用程序有哪些优势?
- ruby - 在不同范围内定义时如何从 lambda 定义中设置实例变量
- excel - Excel函数在另一个单元格中查找任何给定的列值作为子字符串
- javascript - 确定我们是处于撰写模式还是编辑模式
- r - 在 rmarkdown 中使用 htmlwidgets 和revealjs
- spring - Spring Boot 2,分离 AuthorizationServer 和 ResourceServer