python threading 传递参数
时间: 2023-08-24 10:08:09 浏览: 48
可以使用 args 参数来传递参数,例如:
```python
import threading
def worker(num):
print('Worker %d is working...' % num)
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
```
这里定义了一个 worker 函数,每个线程都会调用该函数并传入一个参数。使用 args 参数来传递参数,args 是一个元组,元组中的第一个元素为传递给 worker 函数的第一个参数,第二个元素为传递给 worker 函数的第二个参数,以此类推。
相关问题
python threading.Thread如何传递参数
在 Python 中使用 threading 模块创建线程时,可以使用 `threading.Thread` 类的构造函数来传递参数。具体方法是在创建 `threading.Thread` 实例时,将需要传递的参数作为关键字参数传入构造函数中。例如:
```python
import threading
def my_function(arg1, arg2):
# do something with arg1 and arg2
print(arg1, arg2)
thread = threading.Thread(target=my_function, kwargs={'arg1': 'hello', 'arg2': 'world'})
thread.start()
```
在上面的代码中,我们将 `arg1` 和 `arg2` 作为关键字参数传递给了 `threading.Thread` 构造函数,这样在调用线程的 `start()` 方法时,就可以将这些参数传递给 `my_function` 函数。
threading 传递参数
在 Python 中使用 threading 模块创建线程时,可以通过传递参数来向线程中传递数据。传递参数的方法有以下几种:
1. 使用函数的参数:可以在创建线程时,将需要传递的参数作为函数的参数进行传递。例如:
```python
import threading
def worker(num):
print('Worker:', num)
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
```
2. 使用全局变量:可以在主线程和子线程之间共享一个全局变量,通过修改全局变量的值来传递数据。例如:
```python
import threading
global_var = 0
def worker():
global global_var
global_var += 1
print('Worker:', global_var)
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
```
3. 使用类的属性:可以创建一个带有属性的类,将需要传递的数据作为属性赋值给类,然后在创建线程时将类的实例作为参数进行传递。例如:
```python
import threading
class Worker:
def __init__(self, num):
self.num = num
def run(self):
print('Worker:', self.num)
threads = []
for i in range(5):
w = Worker(i)
t = threading.Thread(target=w.run)
threads.append(t)
t.start()
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)