python等待线程结束_如何等待线程完成后再继续

我需要在另一个线程中运行一个函数,并获取该函数的返回值以将其保存到主线程中的一个变量中。基本上,我的代码调用该函数,该函数通过串行端口与天平通信,等待并获取响应,解析响应,并以浮点形式返回响应。我需要捕捉这个浮动,这样我就可以保存它了。这是我的代码:from multiprocessing.pool import ThreadPool

pool = ThreadPool(processes=2)

result = pool.apply_async(manual_short_command, (self.status_signal2, self.conn, command, status_string, 2))

self.readout = result.get()

def manual_short_command(signal, conn, command, status_string, string_arg='', timeout=60):

""" Send specified command (expects a balance response)to balance through "conn" and emit status signal """

print "Command: " + command.strip('\r\n')

emit_status(signal, status_string[0], string_arg)

if not conn.isOpen():

conn.open()

# Wait until nothing can be read at the balance port

while not timeout and conn.readlines():

time.sleep(1)

timeout -= 1

# Write the command to the balance port and wait for response

while timeout:

time.sleep(1)

conn.write(command)

resp = conn.readlines()

try:

resp = float(resp[0])

except ValueError:

pattern = r'(.?\d+\.\d+)'

match = re.findall(pattern, resp[0])

resp = float(match[0])

except IndexError:

continue

print resp

print 'timeout: %s' % timeout

if resp:

emit_status(signal, status_string[1], str(resp))

print resp, 'here'

return resp

timeout -= 1

conn.close()

print resp

return resp

我在另一个线程中启动函数manual_short_command,这个函数通过串行端口发送一个命令并等待响应。然后它返回这个响应并将其写入状态浏览器(我使用PyQt4作为GUI,但我认为这是不相关的)。在

当我试图分配self.readout = result.get()时,我得到一个错误,说IndexError: list index out of range,这意味着该函数还没有在另一个线程中完成。在分配结果之前如何等待线程完成?否则我的程序挂起。我查看了Threading pool similar to the multiprocessing Pool?以获得一些指导,但是我找不到如何同步这两个线程。有什么建议吗?对不起,代码块太大了。在

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值