-2

我很新,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 提前致谢

4

1 回答 1

2

你真的不能,因为线程都在尝试做同样的事情——打印到标准输出。所以他们只需要继续等待对方。

您想要的方式是最糟糕的结果,因为它需要为每一行输出进行上下文切换,因为一个线程释放标准输出的所有权,另一个线程获取它。最有效的结果是每个线程在等待写入时必须阻塞之前尽可能多地完成工作。

如果您真的想强制执行最差的性能,可以sched_yieldprintf.

如果你想要并发,你为什么要创建一大堆只为相同资源而战的线程?

于 2013-10-05T00:19:05.543 回答