【问题标题】:Python Multi-threading HelpPython 多线程帮助
【发布时间】:2011-06-29 15:51:51
【问题描述】:

我希望在新线程的另一个 python 脚本中调用 python 函数。 我有使用 subprocess.Popen 的经验,但我用它在命令行中调用 .exe。有人推荐如何执行此操作或使用模块吗?

def main(argv):
    call otherdef(1,2,3) in a new thread
    sleep for 10 minutes
    kill the otherdef process

def otherdef(num1, num2, num3):
    while(True):
        print num1

【问题讨论】:

  • 你说in a new thread是指in a new process
  • 不是杀死它,为什么你在 10 分钟后不让进程中止?

标签: python multithreading


【解决方案1】:

这是一个解决方案,但它并不完全像你问的那样,因为杀死一个线程很复杂。最好让线程自行终止,所有线程默认为 daemonic=False (除非其父线程是守护线程),因此当主线程死亡时,您的线程将存活。将其设置为 true,它将与您的主线程一起死亡。

基本上你所做的就是启动一个Thread 并给它一个运行方法。您需要能够传递参数,这样您才能看到我传递了一个 args= 参数,其中包含要传递给目标方法的值。

import time
import threading


def otherdef(num1, num2, num3):
    #Inside of otherdef we use an event to loop on, 
    #we do this so we can have a convent way to stop the process.

    stopped = threading.Event()
    #set a timer, after 10 seconds.. kill this loop
    threading.Timer(10, stopped.set).start()
    #while the event has not been triggered, do something useless
    while(not stopped.is_set()):
        print 'doing ', num1, num2, num3
        stopped.wait(1)

    print 'otherdef exiting'

print 'Running'
#create a thread, when I call start call the target and pass args
p = threading.Thread(target=otherdef, args=(1,2,3))
p.start()
#wait for the threadto finish
p.join(11)

print 'Done'    

目前还不清楚你想要一个进程还是一个线程,但如果你想要一个Process 导入多处理并将threading.Thread( 切换到multiprocessing.Process(,其他一切都保持不变。

【讨论】:

  • "所有线程默认为守护进程" -- 你确定吗?
猜你喜欢
  • 2011-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多