【发布时间】:2015-08-22 04:15:48
【问题描述】:
我正在调用 100 个线程,每个线程应该将一个共享变量递增 1000 次。所以预期的输出应该是 100000。当然当多个线程尝试递增一个共享变量时,你也可以得到不是 100000 的输出(你得到 100000 的可能性不大)。
为了解决这个问题,我在增加变量的方法中加了一个锁,这样一切都同步运行。
但是,我仍然会收到 99000、98000 甚至 100000 之类的数字。但它应该始终是 100000,因为我有锁,对吧?
这就是我所拥有的
volatile unsigned int count = 0;
void *increment(void *vargp);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main() {
fprintf(stdout, "Before: count = %d\n", count);
int j;
// run 10 times to test output
for (j = 0; j < 10; j++) {
// reset count every time
count = 0;
int i;
// create 100 theads
for (i = 0; i < 100; i++) {
pthread_t thread;
Pthread_create(&thread, NULL, increment, NULL);
}
fprintf(stdout, "After: count = %d\n", count);
}
return 0;
}
void *increment(void *vargp) {
int c;
// protected by mutex lock
pthread_mutex_lock(&mutex);
// increment count 1000 times
for (c = 0; c < 1000; c++) {
count++;
}
pthread_mutex_unlock(&mutex);
return NULL;
}
【问题讨论】:
-
始终检查调用 pthread_create() 的返回值以确保操作成功
-
从线程返回/退出时,使用 'pthread_exit( *status );'注意返回(NULL);
-
代码缺少(在 main() 函数中)对“pthread_join()”的 100 次调用,并且只有 1 个线程 ID 条目。它需要 100 个 id 条目,因此对 pthread-join() 的调用可以正常工作。
-
我注意到 pthread_create() 的拼写是 'Pthread_create()' 可能拼写不正确
-
对于每个启动的线程,main() 函数都需要调用 pthread_join() 来等待线程完成
标签: c multithreading mutex concurrent-programming