Job: sample N
ints in {0, 1}
, assign "sampling N_i
ints" to CPU i
. N = N_1 + ... + N_m
. Here is an implementation in Python, where N = 16, m = 4; N_1, N_2, N_3, N_4 = 1, 2, 3, 10
.
import multiprocessing as mp
import time
from random import sample
def func(Library, Timer, nums, pid, t0):
# proc: pid, sample size: nums[pid]
sub_Lib = []
while True:
time.sleep(1)
i = sample(range(2), 1)[0]
Library.append(i)
sub_Lib.append(i)
# self job finished
if len(sub_Lib) == nums[pid]:
Timer[pid] = round(time.time()-t0, 2)
break
# ult job finished
if len(Library) == sum(nums):
Timer[pid] = round(time.time()-t0, 2)
break
pass
pass
def run_process():
Library = mp.Manager().list()
Timer = mp.Manager().dict()
nums = [1, 2, 3, 10]
t0 = time.time()
procs = []
for pid, num in enumerate(nums):
proc = mp.Process(target=func, args=(Library, Timer, nums, pid, t0))
procs.append(proc)
pass
for proc in procs:
proc.start()
pass
for proc in procs:
proc.join()
pass
result = 'Ints: {}\nTime: {}'.format(Library, Timer)
print(result)
pass
def main():
run_process()
pass
if __name__ == '__main__':
main()
pass
请注意,第四工序比其他工序需要更多的时间。3.是否可以订购完成的工序来帮助未完成的工序?任何帮助表示赞赏,在此先感谢您。