python thread 传参
时间: 2023-09-01 13:07:30 浏览: 91
Python的线程(Thread)传参的方法有以下几种:
1. 通过构造函数传参:可以在Thread对象的构造函数中传入可调用对象的参数,例如:
```python
import threading
def worker(num):
print('Worker %d started' % num)
threads = []
for i in range(5):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
```
2. 通过自定义类传参:可以自定义一个类,在类的构造函数中传入需要的参数,然后重写run方法来实现线程。例如:
```python
import threading
class MyThread(threading.Thread):
def __init__(self, num):
threading.Thread.__init__(self)
self.num = num
def run(self):
print('Worker %d started' % self.num)
threads = []
for i in range(5):
t = MyThread(i)
threads.append(t)
t.start()
```
3. 使用全局变量传参:也可以使用全局变量来传递参数,但是需要注意线程安全问题。例如:
```python
import threading
def worker():
global num
print('Worker %d started' % num)
num = 0
threads = []
for i in range(5):
num = i
t = threading.Thread(target=worker)
threads.append(t)
t.start()
```
阅读全文