Multithreading Python3.2_线程模块在使用Ubuntu12.04时不会产生任何输出,但在Windows7中运行良好
我希望有人能快速简单地解决我面临的这个问题。我正在阅读Mark Lutz编写的Python编程书第四版的第5章,从第189页开始,我遇到了一些问题。基本上,有一个非常简单的例子:Multithreading Python3.2_线程模块在使用Ubuntu12.04时不会产生任何输出,但在Windows7中运行良好,multithreading,python-3.x,Multithreading,Python 3.x,我希望有人能快速简单地解决我面临的这个问题。我正在阅读Mark Lutz编写的Python编程书第四版的第5章,从第189页开始,我遇到了一些问题。基本上,有一个非常简单的例子: import _thread def action(i): print(i ** 32) _thread.start_new_thread(action, (2, )) 出于某种原因,这个脚本不会在我运行Ubuntu 12.04的pc上产生任何输出,但会在我的windows 7机器上产生。从终端运行时的输出
import _thread
def action(i):
print(i ** 32)
_thread.start_new_thread(action, (2, ))
出于某种原因,这个脚本不会在我运行Ubuntu 12.04的pc上产生任何输出,但会在我的windows 7机器上产生。从终端运行时的输出为:
un@homepc:~/Desktop/pp$ python3.2 thread1.py
un@homepc:~/Desktop/pp$
任何帮助都将不胜感激
谢谢。我不是线程专家,但这很可能是问题所在: 当运行此代码时,Python在最后一行之后无事可做;因此,它将强制结束线程(无论是否完成)。 根据线程的运行方式,线程可能完成,也可能不完成。(不可靠行为) 主线程伪代码指令: 创建新线程 新线程: 行动(2) 主线程下一个指令: 节目结束;出口 固定代码:
import _thread
def action(i):
print(i ** 32)
action_lock.release() #Now Python will exit
#locks are a part of threaded programming; if you don't know what it is, you can google it.
action_lock = _thread.allocate_lock() #set a lock for the action function thread
action_lock.acquire() #Acquire the lock
_thread.start_new_thread(action, (2, ))
action_lock.acquire()
感谢拉姆钱德拉为我指明了正确的方向。问题是程序正在结束并终止线程。如果我运行这个:
import time, _thread
def print_t(name, delay):
while True:
try:
time.sleep(delay)
print(name)
except: pass
_thread.start_new_thread(print_t, ("First Thread", 1,))
_thread.start_new_thread(print_t, ("Second Thread", 2,))
while True:
try: pass
except KeyboardInterrupt:
print("Ending main program")
break
。。。然后程序按计划执行。我不知道为什么原始帖子中的代码可以在Windows7上运行,但不能在ubuntu 12.04上运行。哦,好吧。希望这对某人有所帮助。感谢您的回复。我很感激。如果我在末尾添加另一行,例如print(“completed”),它将进行打印,但仍然没有其他输出。这个程序在Windows7中正常运行,但在Ubuntu12.04中却无法正常运行,这一事实仍然让我感到困惑。哦,修复后的代码无法工作!!我忘记粘贴正确的代码了!!这不是正确的解决方案-使用锁,如我的答案所示