gpt4 book ai didi

python - 为什么使用 `_thread.start_new_thread` 创建的线程不打印任何内容?

转载 作者:行者123 更新时间:2023-11-30 23:12:36 24 4
gpt4 key购买 nike

我在 https://code.google.com/p/pyloadtools/wiki/CodeTutorialMultiThreading 找到了这个简单的代码

import _thread

def hello(num):
print('hello from thread %s\n' % num)

_thread.start_new_thread(hello, (0,))
_thread.start_new_thread(hello, (1,))
_thread.start_new_thread(hello, (2,))

但是当我运行它时,它可以在 IDLE 上运行,但不能在使用 PyDev 的 eclipse 上运行。知道如何修复它吗?

注意:我认为主程序在线程运行之前终止。我猜线程没有足够的时间来运行。我如何解决它?也许我应该使用 join?

最佳答案

引用 _threadCaveats 部分文档,

  • When the main thread exits, it is system defined whether the other threads survive. On most systems, they are killed without executing try ... finally clauses or executing object destructors.

  • When the main thread exits, it does not do any of its usual cleanup (except that try ... finally clauses are honored), and the standard I/O files are not flushed.

这里有两种可能性。

  1. 主线程启动三个线程,但在线程完成执行之前退出。因此,标准 I/O 文件不会刷新,as they are buffered, by default .

  2. 或者,主线程终止,并且根据引用的第一个要点,所有子线程都在操作中被终止。

无论哪种方式,您都需要确保主线程不会在子线程完成之前终止。

但是当您从 IDLE 运行时,主线程仍然存在,因此,当线程实际完成时,I/O 缓冲区将被刷新。这就是为什么它在 IDLE 中有效但在 Eclipse 中无效。

<小时/>

要确保主线程仅在所有线程完成后退出,可以使其等待子线程

1。 Semaphore

您可以使用信号量,如下所示

import _thread
import threading


def hello(num):
print('hello from thread %s' % num)
# Release semaphore when the thread is actually done
sem.release()


def create_thread(value):
# Acquire semaphore when the thread is actually created
sem.acquire()
_thread.start_new_thread(hello, (value,))

# Counting semaphore. Maximum three threads can acquire.
# Next acquire call has to wait till somebody releases
sem = threading.Semaphore(3)

for i in range(3):
create_thread(i)

# We are capturing the semaphore three times again, because
# whenever a thread completes it releases it. So, only when we
# acquire it thrice to make sure that all threads have completed.
for i in range(3):
sem.acquire()

2. Lock Objects

或者,您可以使用 _thread.lock 对象,如下所示

import _thread

locks = []


def hello(num, lockobject):
print('hello from thread %s' % num)
# Release the lock as we are done here
lockobject.release()


def create_thread(value):
# Create a lock and acquire it
a_lock = _thread.allocate_lock()
a_lock.acquire()

# Store it in the global locks list
locks.append(a_lock)

# Pass it to the newly created thread which can release the lock once done
_thread.start_new_thread(hello, (value, a_lock))

for i in range(3):
create_thread(i)

# Acquire all the locks, which means all the threads have released the locks
all(lock.acquire() for lock in locks)

现在您将看到程序始终打印 hello from 消息。

<小时/>

注意:正如文档所述,_thread 是一个低级线程 API。因此,最好使用更高级别的模块,如 threading ,您可以简单地等待所有线程退出 join方法。

关于python - 为什么使用 `_thread.start_new_thread` 创建的线程不打印任何内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29740478/

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