0

我需要这个结果:

t0 = core 0 Loaded with process 0
t1 = core 1 Loaded with process 1
t2 = core 2 Loaded with process 2
t3 = core 0 Free // a serial processing for each core
t4 = core 0 Loaded with process 3
t5 = core core 1 Free
.... according process 0,1,2,3 takes, in theory the same time on any core

没有p.join()我得到:

t0 = core 0 Loaded with process 0
t1 = core 1 Loaded with process 1
t2 = core 2 Loaded with process 2
t4 = core 0 Loaded with process 3 // two process on core 0
t5 = core 1 Loaded with process 4 // etc etc ...

我得到p.join()

t0 = core 0 Loaded with process 0
t1 = core 0 Free // that is not multiprocessing ...
t2 = core 1 Loaded with process 1
t3 = core 1 Free
t4 = core 2 Loaded with process 2
t5 = core 2 Free

我正在寻找一个if !p.busy()......喜欢或其他什么。目的是将单个进程图像大小调整程序转换为多进程程序。

p.join()来自

p = Process(target=fonction, args=((process_id),filearg[file],t0))
p.start()
p.join()
4

1 回答 1

2

你问的是不可能的。Python 及其模块处理调度。这完全取决于操作系统。如果操作系统认为将核心 X 用于某个进程比使用它更好。时期。

您可以做的最好的事情是更改进程的 CPU 亲和性。您可以使用psutil库来执行此操作,尤其是使用set_cpu_affinity函数。

请注意,根据操作系统和调度程序的关联性可能会或可能不会始终强制执行(即您可以以某种方式设置关联性,但操作系统在某些情况下会忽略它)。


multiprocessing要设置与's实例的 cpu 亲和力,Process您可以执行以下操作:

processes = []
for i in range(4):
    p = Process(target=fonction, args=((process_id),filearg[file],t0))
    p.start()
    proc = psutil.Process(p.pid)
    proc.set_cpu_affinity([i])
    processes.append(p)

# Wait for *all* the child processes to terminate.
for p in processes:
    p.join()

如果您想在 CPU 空闲时重复生成进程,您可以执行以下操作:

processes = []
for i in range(4):
    p = Process(target=fonction, args=((process_id),filearg[file],t0))
    p.start()
    proc = psutil.Process(p.pid)
    proc.set_cpu_affinity([i])
    processes.append(p)

while True:
    for i, p in enumerate(processes):
        if not p.is_alive():
            # this process finished. Replace with a new one.
            p.join()
            new_p = Process(...)
            new_p.start()
            proc = psutil.Process(new_p.pid)
            proc.set_cpu_affinity([i])
            processes[i] = new_p

试着用这种代码玩一下,你应该能够实现,几乎是你想要的输出。

于 2013-08-27T17:53:14.600 回答