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()

python多线程几种方法实现的更多相关文章

  1. python 多线程两种实现方式,Python多线程下的_strptime问题,

    python 多线程两种实现方式 原创 Linux操作系统 作者:杨奇龙 时间:2014-06-08 20:24:26  44021  0 目前python 提供了几种多线程实现方式 thread,t ...

  2. Python多线程及其使用方法

    [Python之旅]第六篇(三):Python多线程及其使用方法   python 多线程 多线程使用方法 GIL 摘要: 1.Python中的多线程     执行一个程序,即在操作系统中开启了一个进 ...

  3. 遍历python字典几种方法

    遍历python字典几种方法 from: http://ghostfromheaven.iteye.com/blog/1549441 aDict = {'key1':'value1', 'key2': ...

  4. mac学习Python第一天:安装、软件说明、运行python的三种方法

    一.Python安装 从Python官网下载Python 3.x的安装程序,下载后双击运行并安装即可: Python有两个版本,一个是2.x版,一个是3.x版,这两个版本是不兼容的. MAC 系统一般 ...

  5. Python使用三种方法实现PCA算法[转]

    主成分分析(PCA) vs 多元判别式分析(MDA) PCA和MDA都是线性变换的方法,二者关系密切.在PCA中,我们寻找数据集中最大化方差的成分,在MDA中,我们对类间最大散布的方向更感兴趣. 一句 ...

  6. 【Python】python 多线程两种实现方式

    目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更 ...

  7. Python类三种方法,函数传参,类与实例变量(一)

    1 Python的函数传递: 首先所有的变量都可以理解为内存中一个对象的'引用' a = 1 def func(a): a = 2 func(a) print(a) # 1 a = 1 def fun ...

  8. JAVA - 多线程 两种方法的比较

    一.继承Thread类 实现方法: (1).首先定义一个类去继承Thread父类,重写父类中的run()方法.在run()方法中加入具体的任务代码或处理逻辑.(2).直接创建一个ThreadDemo2 ...

  9. java--创建多线程两种方法的比较

    [通过继承Thread] 一个Thread对象只能创建一个线程,即使它调用多次的.start()也会只运行一个的线程. [看下面的代码 & 输出结果] package Test; class ...

随机推荐

  1. java虚拟机总结

    jvm内存模型 u  程序计数器 u  Java栈(虚拟机栈) u  本地方法栈 u  Java堆 u  方法区及其运行时常量池 垃圾回收机制 u  新生代和老年代 u  参数设置 u  垃圾回收(M ...

  2. Oracle的substr函数

    一.Substr函数 substr(目标字符串,开始位置,长度) 注意:这里第三个参数:长度,相当于物理中的标量,没有方向性,所以不能用负值.虽然不报错,但是选择不出任何值出来(欢迎指正) 开始位置可 ...

  3. 由typedef和函数指针引起的危机

    由typedef和函数指针引起的危机 昨天阅读了大神强哥的代码,发现里面用到了函数指针,也用到的typedef.本来我自以为对这两个概念有一定的认识,但是突然发现这两个东西居然用到了一起!!!!(在一 ...

  4. python基础:各种类型的转换

    1.str转dict #借助eval,dict str="{"data":"123","result":"ok" ...

  5. 如何选择版本控制系统 ---为什么选择Git版本控制系统

    版本控制系统 "代码"作为软件研发的核心产物,在整个开发周期都在递增,不断合入新需求以及解决bug的新patch,这就需要有一款系统,能够存储.追踪文件的修改历史,记录多个版本的开 ...

  6. Python爬虫一:爬取上交所上市公司信息

    前几天领导让写一个从新闻语料中识别上市公司的方案.上市公司属于组织机构的范畴,组织机构识别属于命名实体识别的范畴.命名实体识别包括人名.地名.组织机构等信息的识别. 要想从新闻语料中识别上市公司就需要 ...

  7. PHP 底层的运行机制与原理 --转

    发现一片总结的还不错的文章,记录一下 PHP说简单,但是要精通也不是一件简单的事.我们除了会使用之外,还得知道它底层的工作原理. PHP是一种适用于web开发的动态语言.具体点说,就是一个用C语言实现 ...

  8. MyBatis 3 User Guide Simplified Chinese.pdf

    MyBatis 3 用户指南 帮助我们把文档做得更好… 如果你发现了本文档的遗漏之处,或者丢失 MyBatis 特性的说明时,那么最好的方法就 是了解一下这个遗漏之处然后把它记录下来. 我们在 wik ...

  9. 第 8 章 MySQL 数据库 Query 的优化

      前言: 在之前“影响 MySQL 应用系统性能的相关因素”一章中我们就已经分析过了Query语句对数据库性能的影响非常大,所以本章将专门针对 MySQL 的 Query 语句的优化进行相应的分析. ...

  10. [转载]OpenStack OVS GRE/VXLAN网络

      学习或者使用OpenStack普遍有这样的现象:50%的时间花费在了网络部分:30%的时间花费在了存储方面:20%的时间花费在了计算方面.OpenStack网络是不得不逾越的鸿沟,接下来我们一起尝 ...