多线程应用探索:Python中的并发编程实例
在Python中,我们可以利用内置的模块如threading
、queue
等进行多线程编程。下面是一些实例:
- 创建线程:
```python
import threading
def thread_function(name):
print(f”Thread {name} started.”)
创建并启动线程
thread_1 = threading.Thread(target=thread_function, args=(“Thread 1”,)))
thread_2 = threading.Thread(target=thread_function, args=(“Thread 2”,)))
thread_1.start()
thread_2.start()
2. **使用`queue`进行生产与消费**:
```python
import queue
# 生产者线程
def producer(q):
for _ in range(5): # 生成5个任务
q.put('Task ' + str(_+1)))
# 消费者线程
def consumer(q):
while not q.empty(): # 只有当队列不为空时才消费
task = q.get()
print(f"Consumed Task {task}.")
if __name__ == "__main__":
# 创建一个无阻塞的队列
q = queue.Queue()
producer(q) # 开始生产者线程
consumer(q) # 启动消费者线程
以上就是Python中多线程编程的一些基本实例。在实际应用中,你可能需要根据具体需求来设计和实现多线程程序。
还没有评论,来说两句吧...