如何使线程频繁进出关键部分

How to make threads going in and out critical section frequently?

本文关键字:出关 键部 何使 线程      更新时间:2023-10-16

我对pthreads很陌生,所以我有一个问题。假设有一个函数,如下所示:

int a=20; //global variable
 void *decrement(void * tid)
{
   while(a>0)
   {
      printf("a= %d accessed by thread %dn",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。我该怎么做?或者有没有办法在不使用 while 循环的情况下只用 6 个线程来完成increment function。PS:不要在乎并发性,因为这是我想要的。:D提前致谢

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

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

如果您真的想强制实现最差的性能,则可以在printf后致电sched_yield

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