python怎样获得线程返回值
Python中可以通过使用`threading`模块的`Thread`类来创建线程,但是线程对象没法直接返回值。如果想要获得线程的返回值,可使用以下两种方法:
1. 使用`threading`模块的`Thread`类的`join()`方法来等待线程的结束,并通过自定义的实例变量来保存线程的返回值。
```python
import threading
class MyThread(threading.Thread):
def __init__(self, *args, **kwargs):
super(MyThread, self).__init__(*args, **kwargs)
self.result = None
def run(self):
# 在run方法中履行线程的操作
# 将结果保存在self.result中
self.result = 42
# 创建线程并启动
thread = MyThread()
thread.start()
# 等待线程结束,并获得结果
thread.join()
result = thread.result
print(result)
```
2. 使用`concurrent.futures`模块的`ThreadPoolExecutor`类来创建线程池,并通过`submit()`方法提交任务,通过返回的`Future`对象的`result()`方法获得线程的返回值。
```python
import concurrent.futures
def my_task():
# 在任务中履行线程的操作
return 42
# 创建线程池
executor = concurrent.futures.ThreadPoolExecutor()
# 提交任务并获得返回的Future对象
future = executor.submit(my_task)
# 获得线程的返回值
result = future.result()
print(result)
```
这两种方法都可以获得到线程的返回值,可以根据具体的需求来选择使用。
TOP