【发布时间】:2015-03-21 23:20:38
【问题描述】:
源代码如下:
#define THREAD 32
#define QUEUE 300
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <assert.h>
#include "threadpool.h"
struct fparam {
int no;
};
int tasks = 0, done = 0;
pthread_mutex_t lock;
int exit_me(){
pthread_mutex_lock(&lock);
tasks--;
pthread_mutex_unlock(&lock);
return 0;
}
void dummy_task(void *arg) {
struct fparam *args = arg;
pthread_mutex_lock(&lock);
done++;
pthread_mutex_unlock(&lock);
printf("Thread INDEX: %d started.\n",args->no);
exit_me();
}
int main()
{
int t, result;
threadpool_t *pool;
struct fparam push_args;
pthread_mutex_init(&lock, NULL);
pool = threadpool_create(THREAD, QUEUE, 0);
fprintf(stderr, "Pool started with %d threads and "
"queue size of %d\n", THREAD, QUEUE);
for (t = 0;t < 2000; t++){
push_args.no = t;
result = threadpool_add(pool, &dummy_task, (void *)&push_args, 0);
if (result == 0){
pthread_mutex_lock(&lock);
tasks++;
pthread_mutex_unlock(&lock);
} else {
printf("Something went wrong with thread: %d\n", t);
}
while(tasks >= QUEUE); // do nothing until tasks running is less than max queue.
}
while(tasks >= 1);
return 0;
}
我正在使用https://github.com/mbrossard/threadpool 池实现。
一切看起来都很好,但是在检查传递给虚拟函数的 t 参数时,我可以看到重复项:
Thread INDEX: 1998 started.
Thread INDEX: 1999 started.
Thread INDEX: 1999 started.
Thread INDEX: 1974 started.
Thread INDEX: 1979 started.
Thread INDEX: 1979 started.
Thread INDEX: 1978 started.
Thread INDEX: 1979 started.
Thread INDEX: 1979 started.
我假设代码中没有任何竞争条件,因为 fparam 结构是在函数内部声明的。
有什么想法或建议吗?
【问题讨论】:
-
通过msan和tsan运行代码。您应该很快发现错误。记住:分享是万恶之源。
标签: c threadpool