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/
python多线程编程的更多相关文章
- 关于python多线程编程中join()和setDaemon()的一点儿探究
关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的 ...
- day-3 python多线程编程知识点汇总
python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...
- python 多线程编程
这篇文章写的很棒http://blog.csdn.net/bravezhe/article/details/8585437 使用threading模块实现多线程编程一[综述] Python这门解释性语 ...
- python多线程编程—同步原语入门(锁Lock、信号量(Bounded)Semaphore)
摘录python核心编程 一般的,多线程代码中,总有一些特定的函数或者代码块不希望(或不应该)被多个线程同时执行(比如两个线程运行的顺序发生变化,就可能造成代码的执行轨迹或者行为不相同,或者产生不一致 ...
- 线程和Python—Python多线程编程
线程和Python 本节主要记录如何在 Python 中使用线程,其中包括全局解释器锁对线程的限制和对应的学习脚本. 全局解释器锁 Python 代码的执行是由 Python 虚拟机(又叫解释器主循环 ...
- python多线程编程(3): 使用互斥锁同步线程
问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的 ...
- python多线程编程-queue模块和生产者-消费者问题
摘录python核心编程 本例中演示生产者-消费者模型:商品或服务的生产者生产商品,然后将其放到类似队列的数据结构中.生产商品中的时间是不确定的,同样消费者消费商品的时间也是不确定的. 使用queue ...
- python 多线程编程之进程和线程基础概念
多线程编程 在多线程(multithreaded,MT)出现之前,计算机程序的执行都是由单个步骤序列组成的,该序列组合在主机的CPU中按照同步顺序执行.无论是任务本身需要按照步骤顺序执行,还是整个过程 ...
- thread模块—Python多线程编程
Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...
随机推荐
- 魔术常量__DIR__
在PHP5.3中,增加了一个新的常量__DIR__,指向当前执行的PHP脚本所在的目录. 例如当前执行的PHP文件为 /www/website/index.php 则__FILE__等于'/www/w ...
- BZOJ 1432: [ZJOI2009]Function
1432: [ZJOI2009]Function Time Limit: 5 Sec Memory Limit: 64 MBSubmit: 1046 Solved: 765[Submit][Sta ...
- Nodejs - 如何用 eventproxy 模块控制并发
本文目标 本文的目标是获取 ZOJ 1001-1010 每道题 best solution 的作者 id,取得数据后一次性输出在控制台. 前文 如何用 Nodejs 分析一个简单页面 我们讲了如何用 ...
- kail linux安装软件提示“无法定位软件包”解决方法
主要是更新源的问题,我安装ibus-pinyin老是提示"无法定位软件包" 最后我用的是163的源: # 源 deb http://mirrors.163.com/debian w ...
- SQL Server 2012复制教程以及复制的几种模式
简介 SQL Server中的复制(Replication)是SQL Server高可用性的核心功能之一,在我看来,复制指的并不仅仅是一项技术,而是一些列技术的集合,包括从存储转发数据到同步数据到维护 ...
- C语言基础(2)-常量
常量就是在程序运行中不可变化的量. #define #define MAX 100 定义了一个常量名字叫MAX,值是100,用#define定义的常量一般用大写字母. #define是一个预编译指令, ...
- javaweb学习总结(五)——Servlet开发(一)
一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...
- golang笔记——struct
1.定义一个结构体 type User struct { userid int username string password string } 2.初始化一个结构体 有两种情况,一是得到结构体的对 ...
- 大熊君大话NodeJS之------MongoDB模块(额外篇)
一,开篇分析 这篇属于扩展知识篇,因为在下面的文章中会用到数据库操作,所以今天就来说说它(Mongodb模块). (1),简介 MongoDB是一个基于分布式文件存储的数据库.由C++语言编写.旨在为 ...
- 守护进程demon.c
1 #include <stdio.h> #include <unistd.h> #include <errno.h> #include <time.h> ...