我很新,pthreads
所以我有一个问题。假设有一个函数,如:
int a=20; //global variable
void *decrement(void * tid)
{
while(a>0)
{
printf("a= %d accessed by thread %d\n",a,tid);
a=a-1;
}
}
在 中main() function
,我创建了 6 个线程:
for(i=0; i < 6; i++) {
pthread_create(&threads[i], NULL, decrement,(void*)i);
}
那么结果将是:
a=20 accessed by theard 0
a=19 accessed by theard 0
a=18 accessed by theard 0
a=17 accessed by theard 0
a=16 accessed by theard 0
a=15 accessed by theard 0
a=14 accessed by theard 0
a=13 accessed by theard 0
a=12 accessed by theard 0
a=11 accessed by theard 0
a=10 accessed by theard 0
...
a=1 accessed by theard 0
a=20 accessed by theard 1
a=20 accessed by theard 2
但我希望它像:
a=20 accessed by theard 0
a=19 accessed by theard 2
a=18 accessed by theard 0
a=17 accessed by theard 1
a=17 accessed by theard 3
a=15 accessed by theard 0
a=14 accessed by theard 2
a=14 accessed by theard 4
a=16 accessed by theard 5
a=15 accessed by theard 1
a=17 accessed by theard 6
...
a=1 accessed by theard 0
a=20 accessed by theard 1
a=20 accessed by theard 2
这意味着6个线程decrement() function
多次进出。我怎样才能做到这一点?或者有什么方法可以在increment function
不使用 while 循环的情况下只使用 6 个线程。PS:不要关心并发,因为那是我想要的。:D 提前致谢