Some Issues need to be helped!
huyeeeee opened this issue · 3 comments
`#include <stdio.h>
#include <pthread.h>
#include "thpool.h"
int c1 = 0;
int count = 0;
void task1(){
int i;
for (i = 0;i < 1000;i++)
count++;
printf("%d Thread %d working on task1\n",count ,c1++);
}
void task2(){
int i;
for (i = 0;i < 1000;i++)
count++;
printf("%dThread %d working on task2\n",count, c1++);
}
int main(){
puts("Making threadpool with 4 threads");
threadpool thpool = thpool_init(4);
puts("Adding 40 tasks to threadpool");
int i;
for (i=0; i<20; i++){
thpool_add_work(thpool, (void*)task1, NULL);
thpool_add_work(thpool, (void*)task2, NULL);
};
thpool_wait(thpool);
puts("Killing threadpool");
thpool_destroy(thpool);
return 0;
}`
the result of this file is variant, I don't know what is going on about this, can someone help me solve this problem? Thanks!
What are the issues? As long as you got the same result in the end, everything is working as expected.
I change the task1() and task2(), the result of the variable count should be 1000*20 = 20000,but the result is less than 20000, and it is variant, I dont know how to make the sub work in the work_queue to work as expected.
the command is: gcc example.c thpool.c -o example.o -lpthread && ./example.o
the result :
Adding 40 tasks to threadpool
1000 Thread 0 working on task1
4000Thread 3 working on task2
5000 Thread 4 working on task1
6000Thread 5 working on task2
7000 Thread 6 working on task1
8000Thread 7 working on task2
9000 Thread 8 working on task1
10000Thread 9 working on task2
11000 Thread 10 working on task1
12000Thread 11 working on task2
13000 Thread 12 working on task1
14000Thread 13 working on task2
2000Thread 1 working on task2
16000Thread 15 working on task2
17000 Thread 16 working on task1
17814Thread 17 working on task2
18355 Thread 18 working on task1
19355Thread 19 working on task2
19819 Thread 20 working on task1
20819Thread 21 working on task2
21376 Thread 22 working on task1
22376Thread 23 working on task2
22880 Thread 24 working on task1
24199 Thread 25 working on task1
25235Thread 27 working on task2
26235 Thread 28 working on task1
27235Thread 29 working on task2
28235 Thread 30 working on task1
29235Thread 31 working on task2
30235 Thread 32 working on task1
31235Thread 33 working on task2
32235 Thread 34 working on task1
33235Thread 35 working on task2
34235 Thread 36 working on task1
35235Thread 37 working on task2
36235 Thread 38 working on task1
37235Thread 39 working on task2
15000 Thread 14 working on task1
24235Thread 26 working on task2
3000 Thread 2 working on task1
Killing threadpool
You're not using the threadpool in a thread-safe way. The c1
and count
are shared by both threads so ofcourse the data will be overriden randomly by any thread that first gets access to it.
So you need to figure out on your own how to make the solution thread-safe (either with atomic variables, semaphores or whatever). The threadpool is working properly.