python多线程的几种方法
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 x lock.acquire() for i in range(3): x = x+1 time.sleep(1) print x lock.release() if __name__ == '__main__': lock = threading.RLock() t1 = [] for i in range(10): t = mythread(str(i)) t1.append(t) x = 0 for 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 x con.acquire() if x == 10000: con.wait() pass else: for i in range(10000): x = x+1 con.notify() print x con.release() class Consumer(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self,name=threadname) def run(self): global x con.acquire() if x == 0: con.wait() pass else: for i in range(10000): x = x-1 con.notify() print x con.release() if __name__ == '__main__': con = threading.Condition() x = 0 p = 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 random class Producer(threading.Thread): def __init__(self,threadname): threading.Thread.__init__(self,name=threadname) def run(self): global queue i = 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 queue item = 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 Queue class Consumer(threading.Thread): def __init__(self, queue): threading.Thread.__init__(self) self._queue = queue def 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 loop break # "Processes" (or in our case, prints) the queue item print "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 = queue def run(self): # variable to keep track of when we started start_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 process self._queue.put('something at %s' % time.time()) # Sleep a bit just to avoid an absurd number of messages time.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': break response = 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 process for url in urls: queue.put(url) # Add the 'quit' message for 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 workers if __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()
参考: http://blog.jobbole.com/58700
转载于:https://www.cnblogs.com/lmpsoftware/p/7787710.html
python多线程的几种方法相关推荐
- Python创建多线程的三种方法
Python创建多线程的三种方法 thread模块函数式创建线程 继承threading类创建多线程 threading模块函数式创建线程 使用总结 thread模块函数式创建线程 调用thread模 ...
- python多线程有几种实现方法
python多线程有几种实现方法,都是什么? 目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而thread ...
- pca算法python代码_三种方法实现PCA算法(Python)
主成分分析,即Principal Component Analysis(PCA),是多元统计中的重要内容,也广泛应用于机器学习和其它领域.它的主要作用是对高维数据进行降维.PCA把原先的n个特征用数目 ...
- python画图-python画图的两种方法
python如何画图?这里给大家介绍两款python绘图的库:turtle和Matplotlib. 1 安装turtle Python2安装命令:pip install turtule Python3 ...
- Python文本处理几种方法
Python文本处理几种方法 方法一:readline函数 #-*- coding: UTF-8 -*- f = open("D:\pythontest\splm_ugslmd.log&qu ...
- Python案例:两种方法实现词频统计
Python案例:两种方法实现词频统计 一.利用字典实现词频统计 1.编写源代码 2.查看运行结果 二.利用collections的Counter模块实现词频统计 <
- java多线程同步的四种方法_java中实现多线程的两种方法
java多线程有几种实现方法,都是什么?同步有几种实java中多线程的实现方法有两种:1.直接继承thread类:2.实现runnable接口:同步的实现方法有五种:1.同步方法:2.同步代码块:3. ...
- 加密Python代码的5种方法
Python越来越热门了,2022年1月编程语言排行榜上挤进第一. Python优点很多,比如简单易学,代码量少,能做的事很多等等,和其他语言一样,Python也有一些不可掩盖的缺点,版本不兼容,运行 ...
- python安装bs4几种方法_Python安装Bs4的多种方法
安装方法一: ①进入python文件夹执行指令(前提是支持pip指令): pip3 install Beautifulsoup4 ②回车待安装完成,如果出现以下红框中内容,即代表安装成功 ③验证是否可 ...
最新文章
- Go语言TCP网络编程(详细)
- 树型结构~无限级联下拉列表框
- win10任务栏透明_Win10 美化软件(简洁篇)
- 利用excel制作二维码
- JS处理文本框只能输入中文、英文、数字,防止SQL特殊字符注入(解决MAC中文输入法下会取得拼音的值的问题)
- QT 字符串转二维码
- 移动端开发使用rem时动态设置html的字体大小
- Web(七)CSS页面布局-网页布局页面的制作
- tracert使用与现象排查
- Linux下at命令的使用!
- 2022年全球市场智能室内空气质量检测仪总体规模、主要生产商、主要地区、产品和应用细分研究报告
- sqlserver日期推算(年,季度,月,星期推算)
- java mcu 视频会议_详解视频会议终端和MCU的区别
- 我是一个功利主义ACMer
- 矩阵的乘法(线性代数及其应用【1】)
- 3.TCP/IP协议,三次握手,四次挥手,UDP协议
- python 数据交互_Python用户交互以及数据类型
- 用计算机弹sunburst,Native Instrument 电吉他音源 Session Guitarist – Electric Sunburst 使用感受...
- 计算机专业知识电子版,事业单位招考计算机专业知识整理.pdf
- CCTV足球解说员速成教材
热门文章
- 操作系统 作业调度实验报告
- 数学知识--Methods for Non-Linear Least Squares Problems(第一章)
- Python 基础 二
- 简易重采样resampler的实现
- 葫芦岛天气预报软件测试,[软件工具][软件游戏]IM智能机器人小强--给你生活带来方便和快乐!(转载)...
- java计算程序运行时间_C#里面的时间,如何计算一个程序运行花费的时间
- airtest web 录制滑块_Airtest 录屏总结,这不是一个简单的 recording!
- cad表示计算机辅助,CAD计算机辅助设计之快捷键篇~( ̄▽ ̄)
- vue.js 发布后路径引用问题
- 解压版mysql安装服务失败怎么办_mysql-8.0.17解压版安装步骤及MySQL服务无法启动问题的解决办法...