Having the source code below:
#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;
}
I'm using https://github.com/mbrossard/threadpool pool implementation.
Everything looks alright, but while checking the t
parameter passed to the dummy function, I can see duplicates:
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.
I suppose given the code that there is not any race condition as the fparam
struct is declared inside the functions.
Any ideas or suggestions?