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多线程编程的更多相关文章

  1. 关于python多线程编程中join()和setDaemon()的一点儿探究

    关于python多线程编程中join()和setDaemon()的用法,这两天我看网上的资料看得头晕脑涨也没看懂,干脆就做一个实验来看看吧. 首先是编写实验的基础代码,创建一个名为MyThread的  ...

  2. day-3 python多线程编程知识点汇总

    python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...

  3. python 多线程编程

    这篇文章写的很棒http://blog.csdn.net/bravezhe/article/details/8585437 使用threading模块实现多线程编程一[综述] Python这门解释性语 ...

  4. python多线程编程—同步原语入门(锁Lock、信号量(Bounded)Semaphore)

    摘录python核心编程 一般的,多线程代码中,总有一些特定的函数或者代码块不希望(或不应该)被多个线程同时执行(比如两个线程运行的顺序发生变化,就可能造成代码的执行轨迹或者行为不相同,或者产生不一致 ...

  5. 线程和Python—Python多线程编程

    线程和Python 本节主要记录如何在 Python 中使用线程,其中包括全局解释器锁对线程的限制和对应的学习脚本. 全局解释器锁 Python 代码的执行是由 Python 虚拟机(又叫解释器主循环 ...

  6. python多线程编程(3): 使用互斥锁同步线程

    问题的提出 上一节的例子中,每个线程互相独立,相互之间没有任何关系.现在假设这样一个例子:有一个全局的计数num,每个线程获取这个全局的计数,根据num进行一些处理,然后将num加1.很容易写出这样的 ...

  7. python多线程编程-queue模块和生产者-消费者问题

    摘录python核心编程 本例中演示生产者-消费者模型:商品或服务的生产者生产商品,然后将其放到类似队列的数据结构中.生产商品中的时间是不确定的,同样消费者消费商品的时间也是不确定的. 使用queue ...

  8. python 多线程编程之进程和线程基础概念

    多线程编程 在多线程(multithreaded,MT)出现之前,计算机程序的执行都是由单个步骤序列组成的,该序列组合在主机的CPU中按照同步顺序执行.无论是任务本身需要按照步骤顺序执行,还是整个过程 ...

  9. thread模块—Python多线程编程

    Thread 模块 *注:在实际使用过程中不建议使用 thread 进行多线程编程,本文档只为学习(或熟悉)多线程使用. Thread 模块除了派生线程外,还提供了基本的同步数据结构,称为锁对象(lo ...

随机推荐

  1. Fiddler 抓包工具总结

    阅读目录 1. Fiddler 抓包简介 1). 字段说明 2). Statistics 请求的性能数据分析 3). Inspectors 查看数据内容 4). AutoResponder 允许拦截制 ...

  2. 教你一招:解决windows xp系统开机出现“disk checking has been canceled”

    问题重现: 问题分析: 系统的注册表被修改了. 问题解决: 1.(临时解决)开机时,按ESC或ENTER键取消. 2.(彻底解决)修改注册表文件. Win + R 打开运行 Regedit ,进入注册 ...

  3. 前端构建工具:gulp的配置与使用

    安装gulp 因为gulp是基于node的管理工具,所以要先安装nodejs安装nodejsnodejs下载地址:中文站:http://nodejs.cn/ 英文站:https://nodejs.or ...

  4. UIActivityViewController 系统社交化 共享

    1.UIActivityViewController是继承自UIViewController,是拥有VC的特性 a.初始化 init  , initWithActivityItems:applicat ...

  5. 选择QT作为自己的图形库

    图形库太多,公司里面一直使用自己的图形库,换一家公司,就换个图形库,现在公司没有对我开放图形库代码. 想来想去还是自己要有一套图形库,拿来主义最方便,选来选去感觉还是QT比较方便.同时能学习一下C++ ...

  6. Alpha阶段项目Postmortem

    以下对成员名字的简称: 陈鸿超 = 陈1 陈彦吉 = 陈2 石浩然 = 石 韩青长 = 韩 1. 设想和目标 1.1 我们的软件要解决什么问题?是否定义得很清楚?是否对典型用户和典型场景有清晰的描述? ...

  7. Oracle 数据导入导出

    一.导出模式(三种模式)及命令格式 1. 全库模式 exp 用户名/密码@网络服务名 full=y file=路径\文件名.dmp log=路径\文件名.log 2. 用户模式(一般情况下采用此模式) ...

  8. 各大主流.Net的IOC框架性能测试比较

    Autofac下载地址:http://code.google.com/p/autofac/ Castle Windsor下载地址:http://sourceforge.net/projects/cas ...

  9. C语言基础(6)-char类型

    1. char常量.变量 使用单引号‘’引起来的就是char的常量 ‘a’是一个char类型的常量 “a”是一个字符串类型的常量 1是一个int型的常量 ‘1’是一个char型的常量 char a; ...

  10. Unity3D 之脚本架构,优雅地管理你的代码

    本文参考雨松MOMO大神的帖子: 图片全部来自他的帖子(请允许我偷懒下) --------------------------------------------------------------- ...