Sva*_*yra 6 python multithreading python-3.x
我试图创建一个具有一个或多个子进程的Python 3程序.
Parent进程生成子进程,然后继续自己的商业,然后我想发送一条消息给特定的子进程,捕获它并采取行动.
此外,子进程在等待消息时需要非锁定,它将运行一个自己的循环来保证服务器连接并将任何已接收的消息发送给父进程.
我目前正在寻找python中的多处理,线程,子进程模块,但一直无法找到任何解决方案.
我想要实现的是让程序的主要部分与用户交互,处理用户输入并向用户呈现信息.这将与来自不同服务器的子部件进行异步,从服务器回收消息并从用户向服务器发送正确的消息.然后,子进程将信息发送回主要部分,并将其提交给用户
我的问题是:
小智 5
请参阅 Doug Hellmann 的(多处理)“进程间通信”。他的本周 Python 模块系列的一部分。使用字典或列表与进程通信相当简单。
import time
from multiprocessing import Process, Manager
def test_f(test_d):
""" frist process to run
exit this process when dictionary's 'QUIT' == True
"""
test_d['2'] = 2 ## change to test this
while not test_d["QUIT"]:
print "test_f", test_d["QUIT"]
test_d["ctr"] += 1
time.sleep(1.0)
def test_f2(name):
""" second process to run. Runs until the for loop exits
"""
for j in range(0, 10):
print name, j
time.sleep(0.5)
print "second process finished"
if __name__ == '__main__':
##--- create a dictionary via Manager
manager = Manager()
test_d = manager.dict()
test_d["ctr"] = 0
test_d["QUIT"] = False
##--- start first process and send dictionary
p = Process(target=test_f, args=(test_d,))
p.start()
##--- start second process
p2 = Process(target=test_f2, args=('P2',))
p2.start()
##--- sleep 3 seconds and then change dictionary
## to exit first process
time.sleep(3.0)
print "\n terminate first process"
test_d["QUIT"] = True
print "test_d changed"
print "data from first process", test_d
time.sleep(5.0)
p.terminate()
p2.terminate()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6179 次 |
| 最近记录: |