我调用了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 = %dn", 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 = %dn", 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;
}
是否等待所有线程完成?你看起来不像。试试这样的问题:我如何等待任何/所有pthreads完成?
下面的代码,在ubuntu Linux 14.04上运行,编译干净,执行正确。
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define UNUSED(x) (void)(x)
#define NUM_TESTS (10)
#define NUM_INCREMENTS (1000)
#define NUM_THREADS (100)
volatile unsigned int count = 0;
void *increment(void *vargp);
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main( void )
{
fprintf(stdout, "Before: count = %dn", count);
pthread_t thread[NUM_THREADS];
int j;
// run 10 times to test output
for (j = 0; j < NUM_TESTS; j++)
{
// reset count every time
count = 0;
int i;
// create 100 theads
for (i = 0; i < NUM_THREADS; i++)
{
pthread_create(&thread[i], NULL, increment, NULL);
}
for( i=0; i < NUM_THREADS; i++ )
{
void *retval;
pthread_join( thread[i], &retval);
}
fprintf(stdout, "After: count = %dn", count);
}
return 0;
}
void *increment(void *vargp)
{
UNUSED(vargp);
int c;
// protected by mutex lock
pthread_mutex_lock(&mutex);
// increment count 1000 times
for (c = 0; c < NUM_INCREMENTS; c++)
{
count++;
}
pthread_mutex_unlock(&mutex);
pthread_exit( NULL );
}