可以使用队列实现在进程间通信(PV操作,类似生产着消费者问题)
from multiprocessing import Queue, Process
import random, time
list1 = ['java', 'python', 'javascript']
def write(queue):
for value in list1:
print(f'正在向队列中写数据-->{value}')
queue.put_nowait(value)
time.sleep(random.random())
def read(queue):
while True:
if not queue.empty():
value = queue.get_nowait()
print(f'从队列中取到的数据为-->{value}')
time.sleep(random.random())
else:
break
queue = Queue()
write_date = Process(target=write, args=(queue,))
read_data = Process(target=read, args=(queue,))
write_date.start()
write_date.join()
read_data.start()
read_data.join()
print('OK!!!')
向线程函数如何传递参数呢?
可以通过Thread类的args参数为线程函数传递参数值。
import threading
#线程函数
def function(s, fun):
print('正在执行函数function')
fun(s)
def ff(s):
print(f'ff输出了{s}')
t1 = threading.Thread(target=function, args=('hello, world', ff))
t1.start()