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

python多线程编程

Python多线程编程中常用方法:

1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout:可选参数,线程运行的最长时间

2、isAlive()方法:查看线程是否还在运行

3、getName()方法:获得线程名

4、setDaemon()方法:主线程退出时,需要子线程随主线程退出,则设置子线程的setDaemon()

Python线程同步:

(1)Thread的Lock和RLock实现简单的线程同步:

import threading
import time
class mythread(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):global xlock.acquire()for i in range(3):x = x+1time.sleep(1)print xlock.release()if __name__ == '__main__':lock = threading.RLock()t1 = []for i in range(10):t = mythread(str(i))t1.append(t)x = 0for i in t1:i.start()

(2)使用条件变量保持线程同步:

# coding=utf-8
import threadingclass Producer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):global xcon.acquire()if x == 10000:con.wait() passelse:for i in range(10000):x = x+1con.notify()print xcon.release()class Consumer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):global xcon.acquire()if x == 0:con.wait()passelse:for i in range(10000):x = x-1con.notify()print xcon.release()if __name__ == '__main__':con = threading.Condition()x = 0p = Producer('Producer')c = Consumer('Consumer')p.start()c.start()p.join()c.join()print x

(3)使用队列保持线程同步:

# coding=utf-8
import threading
import Queue
import time
import randomclass Producer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):global     queuei = random.randint(1,5)queue.put(i)print self.getName(),' put %d to queue' %(i)time.sleep(1)class Consumer(threading.Thread):def __init__(self,threadname):threading.Thread.__init__(self,name=threadname)def run(self):global     queueitem = queue.get()print self.getName(),' get %d from queue' %(item)time.sleep(1)if __name__ == '__main__':queue = Queue.Queue()plist = []clist = []for i in range(3):p = Producer('Producer'+str(i))plist.append(p)for j in range(3):c = Consumer('Consumer'+str(j))clist.append(c)for pt in plist:pt.start()pt.join()for ct in clist:ct.start()ct.join()

生产者消费者模式的另一种实现:

# coding=utf-8
import time
import threading
import Queueclass Consumer(threading.Thread):def __init__(self, queue):threading.Thread.__init__(self)self._queue = queuedef run(self):while True:# queue.get() blocks the current thread until an item is retrieved.msg = self._queue.get()# Checks if the current message is the "quit"if isinstance(msg, str) and msg == 'quit':# if so, exists the loopbreak# "Processes" (or in our case, prints) the queue itemprint "I'm a thread, and I received %s!!" % msg# Always be friendly!print 'Bye byes!'class Producer(threading.Thread):def __init__(self, queue):threading.Thread.__init__(self)self._queue = queuedef run(self):# variable to keep track of when we startedstart_time = time.time()# While under 5 seconds..while time.time() - start_time < 5:# "Produce" a piece of work and stick it in the queue for the Consumer to processself._queue.put('something at %s' % time.time())# Sleep a bit just to avoid an absurd number of messagestime.sleep(1)# This the "quit" message of killing a thread.self._queue.put('quit')if __name__ == '__main__':queue = Queue.Queue()consumer = Consumer(queue)consumer.start()producer1 = Producer(queue)producer1.start()

使用线程池(Thread pool)+同步队列(Queue)的实现方式:

# A more realistic thread pool example
# coding=utf-8
import time 
import threading 
import Queue 
import urllib2 class Consumer(threading.Thread): def __init__(self, queue):threading.Thread.__init__(self)self._queue = queue def run(self):while True: content = self._queue.get() if isinstance(content, str) and content == 'quit':breakresponse = urllib2.urlopen(content)print 'Bye byes!'def Producer():urls = ['http://www.python.org', 'http://www.yahoo.com''http://www.scala.org', 'http://cn.bing.com'# etc.. ]queue = Queue.Queue()worker_threads = build_worker_pool(queue, 4)start_time = time.time()# Add the urls to processfor url in urls: queue.put(url)  # Add the 'quit' messagefor worker in worker_threads:queue.put('quit')for worker in worker_threads:worker.join()print 'Done! Time taken: {}'.format(time.time() - start_time)def build_worker_pool(queue, size):workers = []for _ in range(size):worker = Consumer(queue)worker.start() workers.append(worker)return workersif __name__ == '__main__':Producer()

另一个使用线程池+Map的实现:

import urllib2 
from multiprocessing.dummy import Pool as ThreadPool urls = ['http://www.python.org', 'http://www.python.org/about/','http://www.python.org/doc/','http://www.python.org/download/','http://www.python.org/community/']# Make the Pool of workers
pool = ThreadPool(4) 
# Open the urls in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)
#close the pool and wait for the work to finish 
pool.close() 
pool.join()

相关文章:

python多线程编程

Python多线程编程中常用方法&#xff1a; 1、join()方法&#xff1a;如果一个线程或者在函数执行的过程中调用另一个线程&#xff0c;并且希望待其完成操作后才能执行&#xff0c;那么在调用线程的时就可以使用被调线程的join方法join([timeout]) timeout&#xff1a;可选参数…...

小熊电器:精品与创意,走上“顶流之路”的两把“宝剑”

回顾2022年&#xff0c;小家电市场降温趋势明显&#xff0c;业绩表现整体低迷&#xff0c;如主打高端路线的北鼎&#xff0c;去年8亿元的营收出现个位数下滑&#xff0c;归母净利润同比下降超56%&#xff1b;苏泊尔营收也出现微降&#xff0c;归母净利润预计同比增长不到10%。而…...

如何描述元素与元素间的逻辑关系?

逻辑结构反映的是数据元素之间的关系&#xff0c;它们与数据元素在计算机中的存储位置无关&#xff0c;是数据结构在用户面前所呈现的形式。根据不同的逻辑结构来分&#xff0c;数据结构可分为集合、线性结构、树形结构和图形结构4种形式&#xff0c;接下来分别进行简要介绍。 …...

【3】linux命令每日分享——mv改名或移动

大家好&#xff0c;这里是sdust-vrlab&#xff0c;Linux是一种免费使用和自由传播的类UNIX操作系统&#xff0c;Linux的基本思想有两点&#xff1a;一切都是文件&#xff1b;每个文件都有确定的用途&#xff1b;linux涉及到IT行业的方方面面&#xff0c;在我们日常的学习中&…...

【2023最火教程】Python性能测试框架Locust实战教程(建议收藏)

01、认识Locust Locust是一个比较容易上手的分布式用户负载测试工具。它旨在对网站&#xff08;或其他系统&#xff09;进行负载测试&#xff0c;并确定系统可以处理多少个并发用户&#xff0c;Locust 在英文中是 蝗虫 的意思&#xff1a;作者的想法是在测试期间&#xff0c;放…...

深入浅出C++ ——手撕AVL树

文章目录前言一、AVL 树介绍二、AVL树节点的定义三、AVL树的插入四、AVL树的旋转五、AVL树的验证六、AVL树的删除七、AVL树的性能八、AVL树的实现前言 在前面的文章中介绍了map / multimap / set / multiset 容器&#xff0c;这几个容器的底层都是按照二叉搜索树来实现的。但是…...

将多个springboot项目的pom.xml文件整合

将多个springboot项目的pom.xml文件整合 0.0、前因 ​ 刚入公司敲代码时、发现一个项目中会包含多个子项目、每个子项目会代表一个功能模块、这属实是把我这个菜鸟惊叹到了。而这种分而治之的方式也引申出一个问题&#xff1a;各子项目的依赖如何统一管理&#xff1f; ​ 我…...

【Unity实战100例】Unity串口通讯的消息接收解析和发送指令

目录 一.串口通信介绍 1.串口通信 2.名词介绍 1.上位机: 2.下位机: 3.串行端口...

资源消耗降低 90%,速度提升 50%,解读 Apache Doris Compaction 最新优化与实现

背景LSM-Tree&#xff08; Log Structured-Merge Tree&#xff09;是数据库中最为常见的存储结构之一&#xff0c;其核心思想在于充分发挥磁盘连续读写的性能优势、以短时间的内存与 IO 的开销换取最大的写入性能&#xff0c;数据以 Append-only 的方式写入 Memtable、达到阈值…...

【Mysql】 锁

【Mysql】 锁 文章目录【Mysql】 锁1. 锁1.1 概述1.2 全局锁1.2.1 介绍1.2.2 语法1.2.2.1 加全局锁1.2.2.2 数据备份1.2.2.3 释放锁1.2.3 特点1.3 表级锁1.3.1 介绍1.3.2 表锁1.3.3 元数据锁1.3.4 意向锁1.4 行级锁1.4.1 介绍1.4.2 行锁1.4.3 间隙锁&临键锁1. 锁 1.1 概述…...

Android 流量统计

Android 流量统计最近项目上有一个应用流量统计的功能需要实现&#xff0c;在此总结一下 流量统计架构 在Android9.0之前&#xff0c;流量监控是基于xt_qtaguid模块的&#xff0c;通过读取/proc/net/xt_qtaguid/stats文件内容进行解析获取对应流量数据。 Android9.0之后&…...

如何保证数据的安全?对称和非对称加密,身份认证,摘要算法,数字证书等傻傻分不清?波哥图解带你彻底掌握

支付安全 1.基础概念 明文&#xff1a;加密前的消息叫“明文”&#xff08;plain text&#xff09; 密文&#xff1a;加密后的文本叫“密文”&#xff08;cipher text&#xff09; 密钥&#xff1a;只有掌握特殊“钥匙”的人&#xff0c;才能对加密的文本进行解密&#xff0c;…...

计算机网络概述

目录前言计算机网络的形成<font colorblue>计算机定义与分类计算机网络的定义计算机网络的分类1.按网络的覆盖范围分类2.按网络采用的传输技术分类按网络的拓扑分类计算机网络的组成计算机网络体系结构层次结构体系ISO/OSI 参考模型Tcp/ip体系结构这就是计算机网络的基础…...

小学生学Arduino---------点阵(二)动态图片以及文字

今天进阶了利用人眼视觉暂留原理制作动态的图片变换。 1、熟练掌握图片显示器的使用 2、创作多种动态图片、文字的显示 3、明确动态图片、文字显示过程 4、掌握图片显示器中清空指令的使用 5、搭建动态图片、文字的显示电路 6、编写动态图片、文字的程序 复习&#xff1a; 绘…...

【C语言】-程序编译的环境和预处理详解-让你轻松理解程序是怎么运行的!!

作者&#xff1a;小树苗渴望变成参天大树 作者宣言&#xff1a;认真写好每一篇博客 作者gitee:gitee 如 果 你 喜 欢 作 者 的 文 章 &#xff0c;就 给 作 者 点 点 关 注 吧&#xff01; 程序的编译前言一、 程序的翻译环境和执行环境二、 详解翻译环境2.1编译环境2.1.1预编…...

MapBox动态气泡图渲染教程

先来看效果: 视频效果: 屏幕录制2023-02-22 15.34.57 首先我们来介绍一下思路。对于mapbox和openlayers这样的框架来讲,气泡图中的气泡本质上就是一个div,就是将一个dom元素追加到canvas上的固定位置而已。 在mapbox中有marker的概念,官网也有示例: Attach a popup to …...

在 Ubuntu18.04 上编译安装 GMP

&#xff08;2021.08.04&#xff09;最近为了安装 IBM 的开源项目 HElib C&#xff0c;需要在服务器上先安装GMP和NTL&#xff0c;NTL需要依赖GMP&#xff0c;所以先来安装一下GMP&#xff0c;记录一下在服务器上安装成功的过程&#xff1a;&#xff09; 直接安装libgmp二进制文…...

到底什么样的条件才能被浙大MBA录取?攻略集合

新一年管理类联考已悄然启动&#xff0c;很多考生把目标也都放在了浙江大学MBA项目上&#xff0c;那么浙江大学MBA项目好考吗&#xff1f;报考流程是怎样的&#xff1f;杭州达立易考教育在这里给大家汇总整理了浙大MBA项目相关资讯&#xff0c;分享给想要报考浙大MBA的同学&…...

Impacket工具使用

Impacket工具说明 Impacker是用户处理网络协议的Python类集合,用于对SAB1-3或IPv4/IPv6 上的TCP/UPD/ICMP/IGMP/ARP/IPv4/IPv6/SMB/MSRPC/NTLM/Kerberos/WMI/LDAP 等进行低级的编程访问,数据包可以从头开始构建,也可以从原始数据包中解析, 面向对象API使用处理协议的深层结构变…...

华为OD机试真题Python实现【RSA 加密算法】真题+解题思路+代码(20222023)

RSA 加密算法 题目 RSA 加密算法在网络安全世界中无处不在 它利用了极大整数因数分解的困难度,数据越大安全系数越高 给定了一个32位正整数,请对其进行因数分解 找出哪两个素数的乘积 🔥🔥🔥🔥🔥👉👉👉👉👉👉 华为OD机试(Python)真题目录汇总 ## 输…...

深入剖析AI大模型:大模型时代的 Prompt 工程全解析

今天聊的内容&#xff0c;我认为是AI开发里面非常重要的内容。它在AI开发里无处不在&#xff0c;当你对 AI 助手说 "用李白的风格写一首关于人工智能的诗"&#xff0c;或者让翻译模型 "将这段合同翻译成商务日语" 时&#xff0c;输入的这句话就是 Prompt。…...

React Native 开发环境搭建(全平台详解)

React Native 开发环境搭建&#xff08;全平台详解&#xff09; 在开始使用 React Native 开发移动应用之前&#xff0c;正确设置开发环境是至关重要的一步。本文将为你提供一份全面的指南&#xff0c;涵盖 macOS 和 Windows 平台的配置步骤&#xff0c;如何在 Android 和 iOS…...

阿里云ACP云计算备考笔记 (5)——弹性伸缩

目录 第一章 概述 第二章 弹性伸缩简介 1、弹性伸缩 2、垂直伸缩 3、优势 4、应用场景 ① 无规律的业务量波动 ② 有规律的业务量波动 ③ 无明显业务量波动 ④ 混合型业务 ⑤ 消息通知 ⑥ 生命周期挂钩 ⑦ 自定义方式 ⑧ 滚的升级 5、使用限制 第三章 主要定义 …...

Python:操作 Excel 折叠

💖亲爱的技术爱好者们,热烈欢迎来到 Kant2048 的博客!我是 Thomas Kant,很开心能在CSDN上与你们相遇~💖 本博客的精华专栏: 【自动化测试】 【测试经验】 【人工智能】 【Python】 Python 操作 Excel 系列 读取单元格数据按行写入设置行高和列宽自动调整行高和列宽水平…...

前端倒计时误差!

提示:记录工作中遇到的需求及解决办法 文章目录 前言一、误差从何而来?二、五大解决方案1. 动态校准法(基础版)2. Web Worker 计时3. 服务器时间同步4. Performance API 高精度计时5. 页面可见性API优化三、生产环境最佳实践四、终极解决方案架构前言 前几天听说公司某个项…...

【网络安全产品大调研系列】2. 体验漏洞扫描

前言 2023 年漏洞扫描服务市场规模预计为 3.06&#xff08;十亿美元&#xff09;。漏洞扫描服务市场行业预计将从 2024 年的 3.48&#xff08;十亿美元&#xff09;增长到 2032 年的 9.54&#xff08;十亿美元&#xff09;。预测期内漏洞扫描服务市场 CAGR&#xff08;增长率&…...

算法岗面试经验分享-大模型篇

文章目录 A 基础语言模型A.1 TransformerA.2 Bert B 大语言模型结构B.1 GPTB.2 LLamaB.3 ChatGLMB.4 Qwen C 大语言模型微调C.1 Fine-tuningC.2 Adapter-tuningC.3 Prefix-tuningC.4 P-tuningC.5 LoRA A 基础语言模型 A.1 Transformer &#xff08;1&#xff09;资源 论文&a…...

Fabric V2.5 通用溯源系统——增加图片上传与下载功能

fabric-trace项目在发布一年后,部署量已突破1000次,为支持更多场景,现新增支持图片信息上链,本文对图片上传、下载功能代码进行梳理,包含智能合约、后端、前端部分。 一、智能合约修改 为了增加图片信息上链溯源,需要对底层数据结构进行修改,在此对智能合约中的农产品数…...

Linux 中如何提取压缩文件 ?

Linux 是一种流行的开源操作系统&#xff0c;它提供了许多工具来管理、压缩和解压缩文件。压缩文件有助于节省存储空间&#xff0c;使数据传输更快。本指南将向您展示如何在 Linux 中提取不同类型的压缩文件。 1. Unpacking ZIP Files ZIP 文件是非常常见的&#xff0c;要在 …...

接口自动化测试:HttpRunner基础

相关文档 HttpRunner V3.x中文文档 HttpRunner 用户指南 使用HttpRunner 3.x实现接口自动化测试 HttpRunner介绍 HttpRunner 是一个开源的 API 测试工具&#xff0c;支持 HTTP(S)/HTTP2/WebSocket/RPC 等网络协议&#xff0c;涵盖接口测试、性能测试、数字体验监测等测试类型…...