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 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多线程几种方法实现的更多相关文章
- python 多线程两种实现方式,Python多线程下的_strptime问题,
python 多线程两种实现方式 原创 Linux操作系统 作者:杨奇龙 时间:2014-06-08 20:24:26 44021 0 目前python 提供了几种多线程实现方式 thread,t ...
- Python多线程及其使用方法
[Python之旅]第六篇(三):Python多线程及其使用方法 python 多线程 多线程使用方法 GIL 摘要: 1.Python中的多线程 执行一个程序,即在操作系统中开启了一个进 ...
- 遍历python字典几种方法
遍历python字典几种方法 from: http://ghostfromheaven.iteye.com/blog/1549441 aDict = {'key1':'value1', 'key2': ...
- mac学习Python第一天:安装、软件说明、运行python的三种方法
一.Python安装 从Python官网下载Python 3.x的安装程序,下载后双击运行并安装即可: Python有两个版本,一个是2.x版,一个是3.x版,这两个版本是不兼容的. MAC 系统一般 ...
- Python使用三种方法实现PCA算法[转]
主成分分析(PCA) vs 多元判别式分析(MDA) PCA和MDA都是线性变换的方法,二者关系密切.在PCA中,我们寻找数据集中最大化方差的成分,在MDA中,我们对类间最大散布的方向更感兴趣. 一句 ...
- 【Python】python 多线程两种实现方式
目前python 提供了几种多线程实现方式 thread,threading,multithreading ,其中thread模块比较底层,而threading模块是对thread做了一些包装,可以更 ...
- Python类三种方法,函数传参,类与实例变量(一)
1 Python的函数传递: 首先所有的变量都可以理解为内存中一个对象的'引用' a = 1 def func(a): a = 2 func(a) print(a) # 1 a = 1 def fun ...
- JAVA - 多线程 两种方法的比较
一.继承Thread类 实现方法: (1).首先定义一个类去继承Thread父类,重写父类中的run()方法.在run()方法中加入具体的任务代码或处理逻辑.(2).直接创建一个ThreadDemo2 ...
- java--创建多线程两种方法的比较
[通过继承Thread] 一个Thread对象只能创建一个线程,即使它调用多次的.start()也会只运行一个的线程. [看下面的代码 & 输出结果] package Test; class ...
随机推荐
- 单源最短路Dijkstra算法——matlab实现
迪杰斯特拉(Dijkstra)算法是典型最短路径算法,用于计算一个节点到其他节点的最短路径. 它的主要特点是以起始点为中心向外层层扩展(广度优先搜索思想),直到扩展到终点为止. 基本思想 通过Dijk ...
- oracle的神奇化学反应(行转列+获取表字段)
橘子+汽水=橘子汽水,∑(゚Д゚ノ)ノ好无聊!!! 火鸡+烤架=烤火鸡,ლ(´ڡ`ლ)还不错. wm_concat()+表字段查询=(✪ω✪)会是啥呢? wm_concat()函数,该函数可以把列值以 ...
- Js之on与addEventListener的使用与两者的不同
Js之on和addEventListener的使用与不同 一.首先介绍两者的用法: 1.on的用法:以onclick为例 第一种: obj.onclick = function(){ //do som ...
- 自己编写jQuery动态引入js文件插件 (jquery.import.dynamic.script)
这个插件主要是结合jquery或者xhr异步请求来使用的,它可以把已经引入过的js文件记录在浏览器内存中,当下次再引入相同的文件就忽略该文件的引入. 此插件不支持浏览器刷新保存数据,那需要利用cook ...
- MyBatis之级联——一对多关系
上次我们讲到了MyBatis的一对一关系的表示,简单回顾一下一对一关系就是一个学生只有一个学生证.那么什么是一对多关系呢?一个学生有多个课程这就是一对多的关系.我们结合上一章中的学生和学生证,在此基础 ...
- 重新绑定ItemsSource先设置ItemsSource = null;的原因
即报错信息为:在使用 ItemsSource 之前,项集合必须为空. 原因:Items和ItemSource,只能有一个生效,想用其中一个,另一个必须是空. 重新绑定ItemSource,虽然 ...
- Hive的分区操作~~~~~~
一.Hive分区(一).分区概念:为什么要创建分区:单个表数据量越来越大的时候,在Hive Select查询中一般会扫描整个表内容,会消耗很多时间做没必要的工作.有时候只需要扫描表中关心的一部分数据, ...
- xml注释快捷键
eclipse中编辑Java或C/C++文件时,注释的快捷键均为 "CTRL + / ",编辑xml文件时,该快捷键无效. eclipse XML 注释:CTRL + SHIFT ...
- cassandra.yaml 配置 (非原创,侵删)
Copy from: http://blog.csdn.net/y_h_t/article/details/11917531 Cassandra中所有的运行配置都是在配置文件cassandra.yam ...
- C# MVC权限验证
前言 之前一直没怎么接触过权限验证这块,刚好公司老平台改版,就有了这篇权限验证.此篇文章大致讲解下 精确到按钮级别的验证如何实现.以及权限验证设计的参考思路(菜鸟一枚,大神勿喷). 在开发大项目的时候 ...