我有一个使用 Python 3.4.2 的非常简单的线程示例。在此示例中,我创建了五个线程,仅返回字符串“Result”并将其附加到标题为 thread 的数组中。在另一个迭代五次的 for 循环中,线程被连接到术语 x。我正在尝试打印结果 x,它应该生成一个看起来像 ['Resut','Result','Result','Result','Result'] 的列表,但打印命令仅生成线程的标题以及它已关闭的事实。我显然误解了如何在 python 中使用线程。如果有人可以提供一个如何充分完成此测试用例的示例,我将非常感激。
import threading
def Thread_Test():
return ("Result")
number = 5
threads = []
for i in range(number):
Result = threading.Thread(target=Thread_Test)
threads.append(Result)
Result.start()
for x in threads:
x.join()
print (x)
最佳答案
创建线程和尝试从线程中获取值之间是有区别的。一般来说,您永远不应该尝试在线程中使用 return 来向其调用者提供返回值。这不是线程的工作方式。当您创建线程对象时,您必须找出一种不同的方法来将线程中计算的任何值传递到程序的其他部分。下面是一个简单的示例,展示了如何使用列表返回值。
#! /usr/bin/env python3
import threading
def main():
# Define a few variables including storage for threads and values.
threads_to_create = 5
threads = []
results = []
# Create, start, and store all of the thread objects.
for number in range(threads_to_create):
thread = threading.Thread(target=lambda: results.append(number))
thread.start()
threads.append(thread)
# Ensure all threads are done and show the results.
for thread in threads:
thread.join()
print(results)
if __name__ == '__main__':
main()
如果您绝对坚持必须能够从线程的目标返回值,则可以使用子类覆盖 threading.Thread
中的某些方法来获得所需的行为。下面显示了更高级的用法,并演示了如果有人希望继承并覆盖新类的 run
方法,则多个方法需要更改。提供此代码是为了完整性,可能不应使用。
#! /usr/bin/env python3
import sys as _sys
import threading
def main():
# Define a few variables including storage for threads.
threads_to_create = 5
threads = []
# Create, start, and store all of the thread objects.
for number in range(threads_to_create):
thread = ThreadWithReturn(target=lambda: number)
thread.start()
threads.append(thread)
# Ensure all threads are done and show the results.
print([thread.returned for thread in threads])
class ThreadWithReturn(threading.Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None, *, daemon=None):
super().__init__(group, target, name, args, kwargs, daemon=daemon)
self.__value = None
def run(self):
try:
if self._target:
return self._target(*self._args, **self._kwargs)
finally:
del self._target, self._args, self._kwargs
def _bootstrap_inner(self):
try:
self._set_ident()
self._set_tstate_lock()
self._started.set()
with threading._active_limbo_lock:
threading._active[self._ident] = self
del threading._limbo[self]
if threading._trace_hook:
_sys.settrace(threading._trace_hook)
if threading._profile_hook:
threading. _sys.setprofile(threading._profile_hook)
try:
self.__value = True, self.run()
except SystemExit:
pass
except:
exc_type, exc_value, exc_tb = self._exc_info()
self.__value = False, exc_value
if _sys and _sys.stderr is not None:
print("Exception in thread %s:\n%s" %
(self.name, threading._format_exc()), file=_sys.stderr)
elif self._stderr is not None:
try:
print((
"Exception in thread " + self.name +
" (most likely raised during interpreter shutdown):"), file=self._stderr)
print((
"Traceback (most recent call last):"), file=self._stderr)
while exc_tb:
print((
' File "%s", line %s, in %s' %
(exc_tb.tb_frame.f_code.co_filename,
exc_tb.tb_lineno,
exc_tb.tb_frame.f_code.co_name)), file=self._stderr)
exc_tb = exc_tb.tb_next
print(("%s: %s" % (exc_type, exc_value)), file=self._stderr)
finally:
del exc_type, exc_value, exc_tb
finally:
pass
finally:
with threading._active_limbo_lock:
try:
del threading._active[threading.get_ident()]
except:
pass
@property
def returned(self):
if self.__value is None:
self.join()
if self.__value is not None:
valid, value = self.__value
if valid:
return value
raise value
if __name__ == '__main__':
main()
关于python - 如何从Python线程访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42699837/