我定义 alearner
和 a worker
。我希望它在后台learner
运行其成员函数,并偶尔发送一些信息进行打印。learn
worker
learner
下面的代码是一个例子
import ray
@ray.remote
class Learner():
def __init__(self):
pass
def learn(self):
while True:
pass # do something, such as updating network
def log_score(self, score):
print('worker', score)
@ray.remote
class Worker():
def __init__(self, learner):
self.learner = learner
def sample(self):
for i in range(1000000):
if i % 1000 == 0:
self.learner.log_score.remote(i)
ray.init()
learner = Learner.remote()
worker = Worker.remote(learner)
worker.sample.remote()
learner.learn.remote()
while True:
pass
但是,直到完成learner
才会运行,这不是我想要的。我已经想到了一种使它起作用的方法:我没有显式调用,而是调用它。具体来说,我重新定义并如下log_score
learn
Learner.learn
Worker
learn
sample
"""Learner"""
def learn(self):
# no loop here
pass # do something, such as updating network
"""Worker"""
def sample(self):
for i in range(1000000):
if i % 1000 == 0:
self.learner.learn.remote()
self.learner.log_score.remote(i)
虽然这可行,但现在我必须控制应该多久learn
调用一次,这似乎有点多余。有没有更好的方法来实现我想要的?