My variables is not change
huyeeeee opened this issue · 3 comments
the problem is that I defined a struct to store the variable i changed in a foop loop, but after I added all works, then I use function thpool_wait() to wait the work done, but the result is not as expected, the result should be a list of numbers from 0-99, maybe the sequence is variant, but the result of mine is always 99, hope your help,thanks
the code
`#include "thpool.h"
struct param
{
int i;
};
void subfunc(void *arg)
{
struct param *p = (struct param *)arg;
printf("i = %d\n", p->i);
}
int main()
{
threadpool tp = thpool_init(4);
int i = 0;
struct param p;
for (i = 0; i < 100; i++)
{
p.i = i;
thpool_add_work(tp, subfunc, (void *)&p);
}
thpool_wait(tp);
thpool_destroy(tp);
}`
the result as follow
~/Code/1010$ ./test.o i = 3 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99 i = 99
Because all threads share one parameter. At last, p->i is 99, so most output is 99.
…
Thanks for your help!
1.But the first " i " is 3 and there is also a situation that the result formed as some 99s then a different number such as 12 or some other numbers, every time the result is different.
2.Besides, what should I do to avoid the situation, I want to make every number show one time in this threadpool