如果有一个cpu核心和两个非阻塞不退出的线程,每个线程每次可以占用多长时间cpu?

if there are one cpu core and two threads with non-blocking and non-exit, how long cpu time each thread could occupy each time?

我的问题的更多细节:

the system platform is linux(mac), the thread task is non-blocking and looping. assuming there is only one cpu core, how long cpu time does a thread could occupy each time when there are two threads. how does cpu time change allocated to each thread when the thread number increment.

|------------------ one cpu time of one thread ---------------------|
|-context switch time -|----------- user code running time----------|
|------------A---------|--------------------B-----------------------|

Experience shows that the performance decreasing gradually when thread number becomes too bigger. I think the performance maybe is influenced by the value of A/B(A stands for the time of context switch, B stands for the time of user code running in one cpu time slice of a thread). So if wen know how the cpu time slice changes when thread number increment, could we know the performance of our system.

我想真正了解cpu时间分配,谁能推荐一些关于这方面的好读物或书籍。

事实1:CPU时间未分配,内核周期性踢出拒绝释放的忙循环进程CPU

有一种硬件以恒定的时间间隔产生中断,这种中断称为定时器中断或tick。只有当 tick 到达时,内核才有机会检查当前 运行ning 进程是否占用了太多 muck cpu 资源。如果没有中断触发,该进程将永远控制 cpu,任何其他代码都不可能 运行.

事实 2:设计良好的程序总是在无事可做时释放 CPU。

有几个函数或系统调用可以释放 CPU 资源。例如。 selectepoll_wait、阻塞 read/write、wait_pid 和我最不喜欢的 sleep(我编码了数百万行,sleep 除了在测试用例)。

调用这些函数将释放CPU资源,然后内核可以调度CPU到其他进程。

事实3:当所有进程无事可做并释放CPU时,内核会将CPU置于低功耗模式,功耗低,产生的热量少。

在X86 arch中,内核会使用halt指令将CPU置于低功耗模式,这实际上会传递CPU,如果没有中断到达,[=63= 】 会永远挂掉。 (在 tickless 模式下,如果没有进程处于活动状态,tick 将被禁用,如果没有网络、硬盘、keyboard/mouse 输入或任何中断到达,CPU 将永远挂起,从而节省电池)

事实 4:单个忙循环进程会将单个 CPU 核心使用率提高到 100%

事实 5:简单的繁忙循环过程不会导致 CPU 产生大量热量

没有 I/O 的简单循环、很少的内存访问(非常低的缓存未命中)、很少的分支,还不错。您可以尝试每个核心一个 for (;;) {} 循环,发现您的 CPU 风扇仍在休息。因为它只使用了芯片中很少的门。

游戏通常 运行 为 60fps,一帧为 1s/60 = 16ms。典型的 CPU 周期为 10-50 毫秒,如果游戏发布 CPU,则不能保证它会在接下来的 16 毫秒内重新获得 CPU。所以游戏通常 运行 一个简单的循环,不断检查高精度时钟以更准确地实现帧率。这就是为什么游戏总是占用 100% CPU,无论你的盒子有多强大。

事实 6:在现代系统中,几个忙循环进程不会挂起、冻结、减慢您的系统

调度程序将提高主动释放 CPU 资源的设计良好的进程的优先级,并降低忙循环进程的优先级。在现代系统中,响应您的 keyboard/mouse 输入或 ssh/bash 只需要不到 1% cpu 的资源,因此处理用户输入的进程可以轻松击败繁忙的循环进程并取得控制权CPU 资源。

希望这些可以帮助您了解调度程序的工作原理