我今天刚开始学习线程,并希望通过运行两个带/不带互斥的代码来测试线程的争用状态。
#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>
#include <stdio.h>
#include <windows.h>
#include <stdlib.h>
#define NTHREADS 3
#define ITERATIONS (long long) 1000000000
//pthread_mutex_t mutex;
static long long counter = 0;
static void * thread_f(void * arg) {
unsigned long long i;
(void)arg;
for (i = 0; i != ITERATIONS; i++) {
// pthread_mutex_lock(&mutex);
counter = counter + 1;
// pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main(void) {
pthread_t threads[NTHREADS];
int i;
for (i = 0; i != NTHREADS; i++)
pthread_create(&threads[i], NULL, thread_f, NULL);
for (i = 0; i != NTHREADS; i++)
pthread_join(threads[i], NULL);
printf("expected = %lld, actual = %lld\n", NTHREADS*ITERATIONS, counter);
printf("experienced %lld race conditions\n", NTHREADS*ITERATIONS - counter);
system("pause");
return 0;
}因此,在没有互斥的情况下,程序在cmd上打印出以下行:
预期= 3000000000,实际= 1174158414 经历了1825841586种比赛条件
然而,如果我在代码中放置互斥,并运行程序,cmd弹出,然后关闭自身而不显示任何结果。
我想知道我是否编码错误或误用互斥线,因为我真的不太了解线程。
这是在windows 10中使用visual studio编码的
发布于 2018-12-21 08:44:36
感谢注释中的EOF,我发现代码中没有初始化互斥体。
我只是简单地说:
if (pthread_mutex_init(&mutex, NULL)) {
printf("Something went wrong\n");
return 1;
}主要是这样,现在一切都很好。
https://stackoverflow.com/questions/53881149
复制相似问题