当前位置: 首页 > article >正文

5个python多线程简单示例

示例 1: 基本线程创建

# 示例 1: 基本线程创建
import threading
import time

def print_numbers():
    for i in range(5):
        time.sleep(1)
        print(i)

# 创建线程
thread = threading.Thread(target=print_numbers)

# 启动线程
thread.start()

# 等待线程完成(可选)
thread.join()

print("Thread has finished execution.")



示例 2: 多个线程

# 示例 2: 多个线程
import threading
import time

def print_numbers(thread_name):
    for i in range(5):
        time.sleep(1)
        print("{}:{}".format(thread_name, i))

# 创建并启动多个线程
threads = []
for i in range(3):
    thread = threading.Thread(target=print_numbers, args=("Thread-{}".format(i+1),))
    threads.append(thread)
    thread.start()

# 等待所有线程完成
for thread in threads:
    thread.join()

print("All threads have finished execution.")







示例 3: 使用线程锁

# 示例 3: 使用线程锁
import threading

lock = threading.Lock()
shared_resource = 0

def increment_resource():
    global shared_resource
    for _ in range(100000):
        with lock:
            shared_resource += 1

threads = []
for _ in range(10):
    thread = threading.Thread(target=increment_resource)
    threads.append(thread)
    thread.start()

for thread in threads:
    thread.join()

print("Final value of shared_resource:{}".format(shared_resource))






示例 4: 使用线程池

# 示例 4: 使用线程池
from concurrent.futures import ThreadPoolExecutor

def print_numbers(n):
    for i in range(n):
        print(i)

# 创建一个线程池,最多允许5个线程同时运行
with ThreadPoolExecutor(max_workers=5) as executor:
    # 提交任务到线程池
    futures = [executor.submit(print_numbers, 5) for _ in range(10)]

    # 等待所有任务完成(可选)
    for future in futures:
        future.result()

print("All tasks have finished execution.")





示例 5: 线程间通信(使用队列)

# 示例 5: 线程间通信(使用队列)
"""
在这个示例中,我们使用了一个队列来在生产者线程和消费者线程之间进行通信。
生产者将项目放入队列中,而消费者从队列中取出项目进行处理。当生产者完成
生产后,它发送一个None作为结束信号给消费者,消费者收到信号后停止处理。
"""
import threading
import queue
import time

def producer(q):
    for i in range(5):
        item = "item-{}".format(i)
        q.put(item)
        print("Produced {}".format(item))

def consumer(q):
    while True:
        item = q.get()
        # time.sleep(1)
        if item is None:# 使用None作为结束信号
            break
        print("Consumed {}".format(item))
        q.task_done()

q = queue.Queue()

producer_thread = threading.Thread(target=producer, args=(q,))
consumer_thread = threading.Thread(target=consumer, args=(q,))

producer_thread.start()
consumer_thread.start()

producer_thread.join()
q.put("None") # 发送结束信号给消费者
consumer_thread.join()

print("All items have been produced and consumed.")



http://www.kler.cn/news/329659.html

相关文章:

  • 封装轮播图 (因为基于微博小程序,语法可能有些出入,如需使用需改标签)
  • [Day 77] 區塊鏈與人工智能的聯動應用:理論、技術與實踐
  • java往word中添加水印,往excel中添加图片
  • kafka 换盘重平衡副本 操作流程
  • Java面试——操作系统篇
  • 【PCB工艺】表面贴装技术中常见错误
  • 【高效管理集合】并查集的实现与应用
  • springboot3通过HttpRequest请求soap
  • 躺平成长:微信小程序运营日记第二天
  • C0005.Clion中移动ui文件到新目录后,报错问题的解决
  • 『功能项目』宠物的召唤跟随【79】
  • 有关Python时间戳的计算
  • OpenAI全新多模态内容审核模型上线:基于 GPT-4o,可检测文本和图像
  • lstm实践
  • 如何在 Windows 10 上恢复未保存/删除的 Word 文档
  • C++ 学习,标准库
  • 结构光编解码—正反格雷码解码代码
  • SQL_create_view
  • VR、AR、MR、XR 领域最新科研资讯获取指南
  • CSS链接
  • 查找与排序-快速排序
  • 数造科技入选中国信通院《高质量数字化转型产品及服务全景图》三大板块
  • OpenCV透视变换:原理、应用与实现
  • Mysql 学习——项目实战
  • 企业级版本管理工具(1)----Git
  • WPF之UI进阶--完整了解wpf的控件和布局容器及应用
  • 栏目一:使用echarts绘制简单图形
  • HttpSession使用方法及原理
  • .c、.cpp、.cc、.cxx、.cp后缀的区别
  • YOLOv8改进,YOLOv8改进主干网络为GhostNetV3(2024年华为的轻量化架构,全网首发),助力涨点