[英]Running Two Functions Simultaneously With Time.Sleep() in Python
import threading
import time
array_values = []
def a(array):
time.sleep(1)
array.append('a')
def b(array):
time.sleep(5)
array.append('b')
def runInParallel(*fns):
z = 0
while z < 6:
if __name__ == '__main__':
proc = []
for fn in fns:
p = threading.Thread(target=fn, args=(array_values,))
p.start()
proc.append(p)
for p in proc:
p.join()
z += 1
runInParallel(a, b)
print(array_values)
CURRENT OUTPUT OF CODE当前代码输出
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
The goal however is to get the program to run both so that while function b has the long wait time of 5 seconds, function a is running and only sleeping 1 second.但是,目标是使程序同时运行,以便在功能b的等待时间长为5秒的同时,功能a正在运行,并且仅休眠1秒。
DESIRED OUTPUT期望的输出
['a', 'a', 'a', 'a', 'b', 'a', 'a', 'a', 'a', 'b', 'a', 'a'.....so on]
I have also tried multiprocessing but learned that it doesn't used shared memory making it not right to the same list, any help is awesome!我还尝试了多处理,但是了解到它没有使用共享内存,因此不适合使用同一列表,任何帮助都很棒! Thanks!
谢谢!
import threading
import time
array_values = []
def a(array):
time.sleep(1)
array.append('a')
def b(array):
time.sleep(5)
array.append('b')
def runInParallel(*fns):
z = 0
while z < 6:
if __name__ == '__main__':
proc = []
for fn in fns:
p = threading.Thread(target=fn, args=(array_values,))
p.start()
proc.append(p)
for p in proc:
p.join()
z += 1
runInParallel(a, b)
print(array_values)
CURRENT OUTPUT OF CODE当前代码输出
['a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b', 'a', 'b']
The goal however is to get the program to run both so that while function b has the long wait time of 5 seconds, function a is running and only sleeping 1 second.但是,目标是使程序同时运行,以便在功能b的等待时间长为5秒的同时,功能a正在运行,并且仅休眠1秒。
DESIRED OUTPUT期望的输出
['a', 'a', 'a', 'a', 'b', 'a', 'a', 'a', 'a', 'b', 'a', 'a'.....so on]
I have also tried multiprocessing but learned that it doesn't used shared memory making it not right to the same list, any help is awesome!我还尝试了多处理,但是了解到它没有使用共享内存,因此不适合使用同一列表,任何帮助都很棒! Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.