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

5个python多线程简单示例

示例 1: 基本线程创建

# 示例 1: 基本线程创建
import threading
import timedef 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 timedef 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 threadinglock = threading.Lock()
shared_resource = 0def increment_resource():global shared_resourcefor _ in range(100000):with lock:shared_resource += 1threads = []
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 ThreadPoolExecutordef 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 timedef 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作为结束信号breakprint("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.lryc.cn/news/453527.html

相关文章:

  • Streamlit:用Python快速构建交互式Web应用
  • 深入浅出Vue.js组件开发:从基础到高级技巧
  • Python并发编程挑战与解决方案
  • LeetCode从入门到超凡(五)深入浅出---位运算
  • 一些 Go Web 开发笔记
  • [Go语言快速上手]初识Go语言
  • 基于STM32的智能风扇控制系统设计
  • OpenCV 形态学相关函数详解及用法示例
  • Kafka学习笔记(三)Kafka分区和副本机制、自定义分区、消费者指定分区
  • 华为 HCIP-Datacom H12-821 题库 (31)
  • 占位,凑满减
  • SpringBoot校园资料平台:从零到一的构建过程
  • czx前端
  • Perforce演讲回顾(上):从UE项目Project Titan,看Helix Core在大型游戏开发中的版本控制与集成使用策略
  • 【含文档】基于Springboot+Andriod的成人教育APP(含源码+数据库+lw)
  • CentOS7系统配置Yum环境
  • pyqt打包成exe相关流程
  • 设计模式、系统设计 record part02
  • github双重验证(2FA)启用方法
  • 《Linux从小白到高手》理论篇:Linux的系统服务管理
  • SQL中如何进行 ‘’撤销‘’ 操作-详解
  • Hadoop之WordCount测试
  • Vue和axios零基础学习
  • STM32新建工程-基于库函数
  • matlab入门学习(二)矩阵、字符串、基本语句、函数
  • PC端微信小程序如何调试?
  • 点击按钮提示气泡信息(Toast)
  • 【易社保-注册安全分析报告】
  • 155. 最小栈
  • 用Manim实现高尔顿板(Galton Board)