gpt4 book ai didi

python - 使用 'spawn'启动Redis进程但面临TypeError:无法腌制_thread.lock对象

转载 作者:行者123 更新时间:2023-12-03 06:44:25 24 4
gpt4 key购买 nike

我必须使用“spawn”来启动进程,因为我需要在进程之间传输cuda张量。
但是使用“spawn”创建redis进程始终会遇到TypeError:无法腌制_thread.lock对象
由于某种原因,此代码删除了某些部分
似乎仅使用“fork”可以正常工作

import redis
from torch.multiprocessing import Process

class Buffer(Process):

def __init__(self, name=0, num_peers=2, actor_queue=0, communicate_queue=0):
Process.__init__(self)

#some arguments
self.actor_queue = actor_queue
self.communicate_queue = communicate_queue

pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
self.r = redis.Redis(connection_pool=pool)
self.r.flushall()

async def write(self, r):
#do sth

async def aggregate(self, r):
#do sth

def run(self):
name_process = mp.current_process().name + str(mp.current_process().pid)
print('starting...', name_process)
loop = asyncio.get_event_loop()
asyncio.set_event_loop(loop)
tasks = asyncio.gather(
loop.create_task(self.write(self.r)),
loop.create_task(self.aggregate(self.r)),
)
try:
loop.run_until_complete(tasks)
finally:
loop.close()

if __name__ == '__main__':
mp.set_start_method('spawn')

queue = mp.Queue(maxsize=5)
queue.put('sth')
name = 'yjsp'
num_peers = 2
p =Buffer(name, num_peers, queue, c_queue)
p.start()

最佳答案

问题解决了!
我们应该在run()中定义池和其他内容
原因是:线程驻留在进程内部,并且进程启动子进程以启用并行。线程需要锁来保持资源问题,就像多个进程获取相同的资源并导致死锁一样。
如果我们在run()中定义池,那么当我们进入run()方法时,我们已经处于子进程中。
像这样

    def run(self):
pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True)
r = redis.Redis(connection_pool=pool)
r.flushall()

关于python - 使用 'spawn'启动Redis进程但面临TypeError:无法腌制_thread.lock对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64272938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com