使用 C++11 线程确保每个线程都有机会在给定时间段内执行

Ensure that each thread gets a chance to execute in a given time period using C++11 threads

假设我在 C++11 中有一个多线程程序,其中每个线程控制向用户显示的某些内容的行为。

我想确保在给定程序的一个线程有 运行 的每个时间段 T,每个线程都有机会执行至少时间 [=11] =],以便显示看起来好像所有线程都在同时执行。其思想是基于线程中存储的一些信息,采用分时循环调度机制,强制线程在其时间片结束后等待,而不是依赖于操作系统调度程序。

最好我也想保证每个线程都是实时调度的

万一只能靠操作系统,请问Linux有什么解决办法吗?

这可以吗?怎么样?

不,那不是带有 C++11 线程的 cross-platform possible。调用线程的频率和时长不取决于应用程序。这取决于您使用的操作系统。


但是,仍然有一些功能可以用来标记 os 特殊的 thread/process 非常重要,因此您可以影响这次模糊你的 puroses.

您可以获得依赖于平台的线程句柄以使用 OS 函数。

native_handle_type    std::thread::native_handle //(since C++11)

Returns the implementation defined underlying thread handle.

我只想再次声明,这需要每个平台不同的实现!


微os经常Windows

根据Microsoft documentation

SetThreadPriority function

Sets the priority value for the specified thread. This value, together with the priority class of the thread's process determines the thread's base priority level.


Linux/Unix

对于 Linux 事情更困难,因为有不同的系统如何安排线程。在 Microsoft Windows 下,它使用优先级系统,但在 Linux 上,这似乎不是默认调度。

更多信息,请查看this Whosebug question(Should be the same for std::thread because of this)。

I want to ensure that for every time period T during which one of the threads of the given program have run, each thread gets a chance to execute for at least time t, so that the display looks as if all threads are executing simultaneously.

您正在使用线程来使不同的任务看起来好像在同时执行。出于 Arthur 的回答中所述的原因,不推荐这样做,我真的无法添加任何内容。

如果不是让长寿命线程各自执行自己的任务,您可以拥有一个可以在没有互斥的情况下执行的任务队列 - 您可以拥有一个任务队列和一个线程池,用于出队和执行任务。

如果不能,您可能需要研究无等待数据结构和算法。在 wait free algorithm/data 结构中,保证每个线程在有限(甚至指定)数量的步骤中完成其工作。我可以推荐这本书 The Art of Multiprocessor Programming,其中详细讨论了这个主题。它的要点是:每个无锁 algorithm/data 结构都可以通过添加线程之间的通信来修改为无等待,即将工作的线程确保没有其他线程 starved/stalled。基本上,比所有线程的总吞吐量更喜欢公平。根据我的经验,这通常不是一个好的妥协。