如何让线程经常进出关键部分?

时间:2013-10-05 00:17:14

标签: c++ pthreads

我对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只有6个线程而不使用while循环。 PS:不要关心并发,因为这就是我想要的。 :d 提前谢谢

1 个答案:

答案 0 :(得分:2)

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

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

如果您真的想要强制性能最差,可以在sched_yield之后拨打printf

如果你想要并发,你为什么要创建一大堆线程,除了争夺相同的资源之外什么都不做?