Python如何执行多线程
时间: 2023-11-05 18:10:39 浏览: 26
Python可以使用threading模块来执行多线程。以下是一个简单的例子:
```python
import threading
def worker():
"""要执行的工作"""
print('Hello, World!')
threads = []
for i in range(5):
t = threading.Thread(target=worker)
threads.append(t)
t.start()
# 等待所有线程执行完毕
for t in threads:
t.join()
```
上面的代码创建了5个线程,每个线程都调用worker函数来执行工作。使用join()方法可以等待所有线程执行完毕。
相关问题
Python执行多线程
Python支持多线程,可以使用threading模块来实现多线程。
1. 创建线程
使用threading.Thread()方法来创建线程,需要传入一个函数作为参数,该函数为线程的执行体。
```python
import threading
def print_hello():
print("Hello world!")
t = threading.Thread(target=print_hello)
t.start()
```
2. 线程同步
线程同步是指多个线程在访问共享资源时,需要协调彼此的执行顺序,以避免出现竞态条件。Python提供了Lock、RLock、Semaphore、Condition等多种线程同步机制。
```python
import threading
count = 0
lock = threading.Lock()
def increment():
global count
for i in range(1000000):
lock.acquire()
count += 1
lock.release()
t1 = threading.Thread(target=increment)
t2 = threading.Thread(target=increment)
t1.start()
t2.start()
t1.join()
t2.join()
print("Count: ", count)
```
在上面的例子中,使用Lock来保护共享变量count,防止两个线程同时修改count的值。
3. 线程间通信
在多线程编程中,线程之间需要进行通信,以便协调彼此的执行。Python提供了Queue模块来实现线程间通信。
```python
import threading
import queue
q = queue.Queue()
def producer():
for i in range(10):
q.put(i)
print("Produced:", i)
def consumer():
while True:
item = q.get()
if item is None:
break
print("Consumed:", item)
q.task_done()
t1 = threading.Thread(target=producer)
t2 = threading.Thread(target=consumer)
t1.start()
t2.start()
t1.join()
q.put(None)
t2.join()
```
在上面的例子中,使用Queue模块来实现生产者-消费者模式的线程间通信。生产者线程向队列中放入数据,消费者线程从队列中取出数据进行处理。当生产者线程放入None时,表示队列中没有更多数据,消费者线程退出。
python多线程执行
Python多线程执行可以使用threading模块来实现。该模块提供了创建和管理线程的功能。可以通过以下方式来创建线程:
示例代码1:
```
import time
import threading
def test():
time.sleep(10)
for i in range(10):
print(i)
thread1 = threading.Thread(target=test)
thread1.start()
print('主线程完成了')
```
在这个例子中,我们首先定义了一个函数test(),该函数会在启动线程后执行。然后我们创建了一个Thread对象,将test()函数作为target参数传入,并调用start()方法启动线程。最后,在主线程中打印了一条完成信息。执行此代码时,主线程会启动一个新的子线程去执行test()函数,同时主线程继续执行后续代码。
示例代码2:
```
import time
import threading
def test():
time.sleep(5)
for i in range(10):
print(i)
thread1 = threading.Thread(target=test)
thread1.start()
thread1.join()
print('主线程完成了')
```
在这个例子中,与前面的示例不同之处在于在主线程中调用了thread1.join()方法。该方法会阻塞主线程,直到thread1线程执行完成后才会继续执行主线程的后续代码。这样可以确保在主线程完成之前,子线程的任务能够得到执行完毕。
注意,Python的多线程由于全局解释器锁(GIL)的存在,无法充分利用多核CPU的计算能力。如果想要充分发挥多核CPU的计算能力,可以考虑使用multiprocessing模块。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [Python多线程简介](https://blog.csdn.net/qq_43590221/article/details/103217631)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
- *2* *3* [python的多线程](https://blog.csdn.net/weixin_61805348/article/details/125021831)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]