python多线程的几种方法

python多线程的几种方法python多线程编程Python多线程编程中常用方法:1、join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程

大家好,又见面了,我是你们的朋友全栈君。

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 threading class 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://javaforall.net/155878.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • Java中,为什么byte类型的取值范围为-128~127?

    Java中,为什么byte类型的取值范围为-128~127?在学习Java基础语法的时候,初学者的我们可能都会有这么一个疑问为什么byte类型的取值范围为什么是[-128,127]而不是[-127,127]。01111111表示最大的数值:127,因为第一位是符号位,所以11111111应该是最小的数值:-127,不是这样才对?在解释这个问题之前我们需要了解几个概念:机器数、真值、原码、反码、补码机器数:一个数在计算机中的二进制表示形式,叫做这个数的机器

    2022年6月15日
    25
  • java标识符与关键字_4、Java标识符和关键字

    java标识符与关键字_4、Java标识符和关键字标识符:Java对各种变量,方法和类等要素命名时使用的字符序列称为标识符。(凡是自己可以起名的地方都叫标识符,都遵循标识符的规则)Java的命名规则:1、标识符由字母、下划线”_”、美元符”$”或数字组成;2、标识符应以字母、下划线、美元符开头;3、Java标识符大小写敏感,长度无限制;4、Java标识符选取应注意“见明知意”且不能与Java语言的关键字重名(约定俗成)合法的标识符HelloWor…

    2022年7月7日
    19
  • ODB学习笔记之基础环境搭建

    ODB学习笔记之基础环境搭建一,简介ODB是应用于C++的一个开源、跨平台、跨数据库的对象关系映射(ORM)系统。它可以让你持久化C++对象到关系数据库,而不必处理表、列或者SQL,无需手动编写任何映射代码。ODB支持My

    2022年8月2日
    6
  • cmd 里面运行git提示“不是内部或外部命令,也不是可运行的程序”的解决办法…「建议收藏」

    cmd 里面运行git提示“不是内部或外部命令,也不是可运行的程序”的解决办法…

    2022年2月8日
    248
  • 浙江python课程_浙江八年级新增Python编程课程!是谁将少儿编程推上风口?

    浙江python课程_浙江八年级新增Python编程课程!是谁将少儿编程推上风口?浙江消息,今年9月份开始的新学期,三到九年级信息技术课将同步替换新器材。其中,八年级将新增Python课程内容。新高一信息技术编程语言由VB替换为Python,大数据、人工智能、程序设计与算法按照教材规划五六年级开始接触。不得不说,在“少儿编程”这条路上,浙江省算是“死磕”到底了。早在2014年,浙江就发布了《浙江省深化高校考试招生制度综合改革试点方案》,方案提到:把信息技术(含编程)正式纳入高考…

    2022年5月17日
    45
  • 关于docker中执行docker命令的实践

    关于docker中执行docker命令的实践最近在制作给kubernetesjenkinsplugin调用的jenkinsslave(默认情况下,kubernetesjenkins插件使用的是jenkinsci/jnlp-slave)容器镜像,以供自动创建的pod使用。对这个镜像的需求是:希望在pod运行的容器内,执行docker命令,完成dockerbuild,push等一些操作,即dockerindocker。首先,需要在

    2022年5月13日
    43

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号