用Python写一个多线程执行类里面一个函数的代码
时间: 2023-04-11 13:01:07 浏览: 72
可以回答这个问题。以下是一个示例代码:
```python
import threading
class MultiThreadExecutor:
def __init__(self):
self.lock = threading.Lock()
def execute(self, func, args_list):
threads = []
for args in args_list:
thread = threading.Thread(target=self._execute_func, args=(func, args))
threads.append(thread)
thread.start()
for thread in threads:
thread.join()
def _execute_func(self, func, args):
with self.lock:
func(*args)
```
这个类可以用来执行一个函数,并行地在多个线程中运行。使用方法如下:
```python
def my_func(arg1, arg2):
# do something with arg1 and arg2
pass
executor = MultiThreadExecutor()
args_list = [(1, 2), (3, 4), (5, 6)]
executor.execute(my_func, args_list)
```
这个示例代码中,`MultiThreadExecutor` 类有一个 `execute` 方法,它接受一个函数和一个参数列表作为参数。`execute` 方法会在多个线程中并行地执行这个函数,每个线程使用参数列表中的一个参数调用函数。在执行函数时,使用了一个锁来保证线程安全。