Python创建线程池
时间: 2023-11-05 19:10:59 浏览: 90
Python中可以通过threading和concurrent.futures模块来创建线程池。使用threading的方式可以自己手动添加线程到线程池中,而使用concurrent.futures则可以更方便地实现线程池的创建和管理,具体实现可参考以下代码:
使用threading:
```python
import threading
class ThreadPool:
def __init__(self, num_threads):
self._threads = [threading.Thread(target=self._worker) for _ in range(num_threads)]
self._task_queue = []
self._lock = threading.Lock()
for thread in self._threads:
thread.start()
def submit(self, func, *args, **kwargs):
self._task_queue.append((func, args, kwargs))
def _worker(self):
while True:
with self._lock:
if len(self._task_queue) > 0:
task = self._task_queue.pop()
else:
continue
func, args, kwargs = task
func(*args, **kwargs)
# Example usage
def print_message(msg):
print(f"Message: {msg}")
thread_pool = ThreadPool(num_threads=4)
for i in range(10):
thread_pool.submit(print_message, f"Hello from thread {i}")
# Output
# Message: Hello from thread 0
# Message: Hello from thread 1
# Message: Hello from thread 2
# Message: Hello from thread 3
# Message: Hello from thread 4
# Message: Hello from thread 5
# Message: Hello from thread 6
# Message: Hello from thread 7
# Message: Hello from thread 8
# Message: Hello from thread 9
```
使用concurrent.futures:
```python
from concurrent.futures import ThreadPoolExecutor
# Example usage
def print_message(msg):
print(f"Message: {msg}")
with ThreadPoolExecutor(max_workers=4) as executor:
for i in range(10):
executor.submit(print_message, f"Hello from thread {i}")
# Output
# Message: Hello from thread 0
# Message: Hello from thread 1
# Message: Hello from thread 2
# Message: Hello from thread 3
# Message: Hello from thread 4
# Message: Hello from thread 5
# Message: Hello from thread 6
# Message: Hello from thread 7
# Message: Hello from thread 8
# Message: Hello from thread 9
```
以上代码只是一个简单的示例,线程池在实际应用中需要根据具体的场景进行合理的设计和使用。
阅读全文