如何使线程频繁进出关键部分
How to make threads going in and out critical section frequently?
我对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
。
如果你想要并发,为什么要创建一大堆线程,除了争夺相同的资源之外什么都不做?
相关文章:
- 使用一个考虑到std::map中键值的滚动或换行的键
- 如何在c++中只将键插入到bimap的一侧
- 使用2个键的cpp-stl::优先级队列排序不正确
- 有效地使用std::unordered_map来插入或增加键的值
- C++映射有2个键,这样任何1个键都可以用来获取值
- 智能指针作为无序映射键,并通过引用进行比较
- 带有数组键C++的二进制映射
- 如何将部分流作为参数传递
- 使用 GLUT 使用键停止动画?
- 无法添加多个键以映射将结构作为键
- 将 std::set 与基于键的比较器一起使用
- 如何使用 std::variant 打印地图键/值?
- 使用模板化的键类型定义 std::map,该键类型基于作为参数接收的函数
- 如何接受 [ENTER] 键作为无效输入并发送错误消息
- C++读取用户输入而不按回车键(Mac OS X),与Turbo Pascal中的读取键相同
- 查找自动生成键并具有线性内存消耗的小型关联数组
- 整数键映射到头文件中的成员函数指针
- 使用字符数组作为 Map 中的键
- (SFML)按下键时,播放器构造函数未使用正确的动画进行更新
- 容器,其中每个项可以有多个非唯一键 (c++17)