单核上的多处理? [英] Multiprocessing on a single core?

查看:54
本文介绍了单核上的多处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用以下示例来尝试 &找出 Python 中的 multiprocessing 模块,但随后我开始怀疑,当你尝试 & 时会发生什么?单核 CPU 上的多进程?下面这个例子到底会发生什么?我认为它会运行,但到底会发生什么?

I was using this following example to try & figure out the multiprocessing module in Python, but then I started to wonder, what happens when you try & multiproccess on a single core CPU? What exactly would happen with this following example? I assume it would run, but what exactly would be happening under the hood?

import os
import random
import sys
import time
import multiprocessing
from multiprocessing import pool

if __name__ == '__main__':
def worker(number):
    sleep = random.randrange(1, 10)
    time.sleep(sleep)
    print("I am Worker {}, I slept for {} seconds".format(number, sleep))

for i in range(5):
    t = multiprocessing.Process(target=worker, args=(i,))
    t.start()

print("All Processes are queued, let's see when they finish!")

推荐答案

操作系统的功能之一就是任务调度.这正是会发生的事情.您的所有线程都将被添加到调度程序列表中,它会定期检查每个任务并在短时间内运行每个任务.由于您的所有工作人员所做的都是睡眠,因此它可能只会在开始和结束时检查它们(睡眠的系统调用告诉调度程序该任务在一段时间内不需要任何处理).

One of the functions of the operating system is task scheduling. And that is exactly what would happen. All your threads would be added to the scheduler list and it would check on each task regularly and run each one for a short time. Since all your workers do is sleep, it would probably only check on them at the start and at the end (the system call for sleep tells the scheduler that the task is not going to need any processing for some time).

这篇关于单核上的多处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆