python 子线程阻塞主线程,python退出阻塞线程?

In my code I loop though raw_input() to see if the user has requested to quit. My app can quit before the user quits, but my problem is the app is still alive until I enter a key to return from the blocking function raw_input(). Can I do to force raw_input() to return by maybe sending it a fake input? Could I terminate the thread that it's on? (the only data it has is a single variable called wantQuit).

解决方案

You can use this time out function that wraps your function. Here's the recipe from: http://code.activestate.com/recipes/473878/

def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):

'''This function will spwan a thread and run the given function using the args, kwargs and

return the given default value if the timeout_duration is exceeded

'''

import threading

class InterruptableThread(threading.Thread):

def __init__(self):

threading.Thread.__init__(self)

self.result = default

def run(self):

try:

self.result = func(*args, **kwargs)

except:

self.result = default

it = InterruptableThread()

it.start()

it.join(timeout_duration)

if it.isAlive():

return it.result

else:

return it.result

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值