task_master.py
import random, queue
from multiprocessing.managers import BaseManager
#建立发布任务和接受结果的队列
task_queue = queue.Queue()
result_queue = queue.Queue()
#通过manger把队列暴露到网络上
class QueueManager(BaseManager):
pass
def get_task_queue():
global task_queue
return task_queue
def get_result_queue():
global result_queue
return result_queue
QueueManager.register('put_task',callable = get_task_queue)
QueueManager.register('get_result',callable = get_result_queue)
def startManager(host,port,key):
#绑定ip和端口,设置验证码
manager = QueueManager(address = (host,port),authkey = key)
manager.start()
return manager
if __name__ == '__main__':
manager = startManager('127.0.0.1',5000,b'abc')
#通过网络获得对象
task = manager.put_task()
#发布任务
for i in range(10):
n = random.randint(1,1000)
task.put(n)
print('put task param >>> %d' % n)
print('try to get result...')
#获取worker端得到的结果
result = manager.get_result()
for i in range(10):
ans = result.get()
print('get result: %s' % ans)
manager.shutdown()
print('master exit')
task_worker.py
import queue,time
from multiprocessing.managers import BaseManager
#从网络上获取队列
class QueueManager(BaseManager):
pass
QueueManager.register('put_task')
QueueManager.register('get_result')
def connectManager(addr,port,key):
manager = QueueManager(address = (addr,port), authkey = key)
manager.connect()
return manager
if __name__ == '__main__':
addr = '127.0.0.1'
print('begin connect %s...' % addr)
manager = connectManager(addr,5000,b'abc')
#从网络上获取队列
task = manager.put_task()
result = manager.get_result()
for i in range(10):
n = task.get()
print('run task %d*%d...' % (n,n))
#计算结果并发回去
ans = '%d*%d = %d' % (n,n,n*n)
time.sleep(1)
result.put(ans)
print('worker exit')
在自己电脑上开两个命令行跑没问题,但是把task_worker.py放另一台电脑上跑报错: