我正在研究Python中的多处理,并试图创建2个进程并通过Pipe在它们之间交换数据。
在下面的代码中,我期望sender
每秒向receiver
发送一个随机整数,然后receiver
将该值写入文件multi.txt
。
但是即使运行代码后文件也为空。该代码的问题是什么?我是否在某处误解了某些东西或犯了错误?
import multiprocessing as mp
import time
import random
import os
pipe1, pipe2 = mp.Pipe()
class sender(mp.Process):
def __init__(self):
mp.Process.__init__(self)
def run(self):
print('SENDER PID: ', os.getpid() )
while True:
value = random.randint(0, 10)
pipe1.send(value)
#print(pipe2.recv()) # <--- prints out value without problems
time.sleep(1)
class receiver(mp.Process):
def __init__(self):
mp.Process.__init__(self)
def run(self):
print('RECEIVER PID: ', os.getpid() )
while True:
#print(pipe2.recv()) # <--- doesn't print out value or write it to file
os.chdir('C:\\Users\\J\\Desktop\\NEW_TRO')
file = open("multi.txt", "a")
file.write(pipe2.recv())
file.close()
if __name__ == '__main__':
print('MAIN PID: ', os.getpid() )
p1 = sender()
p2 = receiver()
p1.start()
p2.start()
#mp.freeze_support()