




已阅读5页,还剩7页未读, 继续免费阅读
版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领
文档简介
Python多线程学习 一、Python中的线程使用: Python中使用线程有两种方式:函数或者用类来包装线程对象。1、 函数式:调用thread模块中的start_new_thread()函数来产生新线程。如下例: view plaincopy to clipboardprint?1 import time 2 import thread 3 def timer(no, interval): 4 cnt = 0 5 while cnt= 5: 59 print Thread %s released! num=%s%(name,str(num) 60 mylock.release() 61 thread.exit_thread() 62 num+=1 63 print Thread %s released! num=%s%(name,str(num) 64 mylock.release() #Release the lock. 65 66 def test(): 67 thread.start_new_thread(add_num, (A,) 68 thread.start_new_thread(add_num, (B,) 69 70 if _name_= _main_: 71 test() Python 在thread的基础上还提供了一个高级的线程控制库,就是之前提到过的threading。Python的threading module是在建立在thread module基础之上的一个module,在threading module中,暴露了许多thread module中的属性。在thread module中,python提供了用户级的线程同步工具“Lock”对象。而在threading module中,python又提供了Lock对象的变种: RLock对象。RLock对象内部维护着一个Lock对象,它是一种可重入的对象。对于Lock对象而言,如果一个线程连续两次进行acquire操作,那么由于第一次acquire之后没有release,第二次acquire将挂起线程。这会导致Lock对象永远不会release,使得线程死锁。RLock对象允许一个线程多次对其进行acquire操作,因为在其内部通过一个counter变量维护着线程acquire的次数。而且每一次的acquire操作必须有一个release操作与之对应,在所有的release操作完成之后,别的线程才能申请该RLock对象。下面来看看如何使用threading的RLock对象实现同步。 view plaincopy to clipboardprint?72 import threading 73 mylock = threading.RLock() 74 num=0 75 76 class myThread(threading.Thread): 77 def _init_(self, name): 78 threading.Thread._init_(self) 79 self.t_name = name 80 81 def run(self): 82 global num 83 while True: 84 mylock.acquire() 85 print nThread(%s) locked, Number: %d%(self.t_name, num) 86 if num=4: 87 mylock.release() 88 print nThread(%s) released, Number: %d%(self.t_name, num) 89 break 90 num+=1 91 print nThread(%s) released, Number: %d%(self.t_name, num) 92 mylock.release() 93 94 def test(): 95 thread1 = myThread(A) 96 thread2 = myThread(B) 97 thread1.start() 98 thread2.start() 99 100 if _name_= _main_: 101 test() 我们把修改共享数据的代码成为“临界区”。必须将所有“临界区”都封闭在同一个锁对象的acquire和release之间。2、 条件同步锁只能提供最基本的同步。假如只在发生某些事件时才访问一个“临界区”,这时需要使用条件变量Condition。Condition对象是对Lock对象的包装,在创建Condition对象时,其构造函数需要一个Lock对象作为参数,如果没有这个Lock对象参数,Condition将在内部自行创建一个Rlock对象。在Condition对象上,当然也可以调用acquire和release操作,因为内部的Lock对象本身就支持这些操作。但是Condition的价值在于其提供的wait和notify的语义。条件变量是如何工作的呢?首先一个线程成功获得一个条件变量后,调用此条件变量的wait()方法会导致这个线程释放这个锁,并进入“blocked”状态,直到另一个线程调用同一个条件变量的notify()方法来唤醒那个进入“blocked”状态的线程。如果调用这个条件变量的notifyAll()方法的话就会唤醒所有的在等待的线程。如果程序或者线程永远处于“blocked”状态的话,就会发生死锁。所以如果使用了锁、条件变量等同步机制的话,一定要注意仔细检查,防止死锁情况的发生。对于可能产生异常的临界区要使用异常处理机制中的finally子句来保证释放锁。等待一个条件变量的线程必须用notify()方法显式的唤醒,否则就永远沉默。保证每一个wait()方法调用都有一个相对应的notify()调用,当然也可以调用notifyAll()方法以防万一。生产者与消费者问题是典型的同步问题。这里简单介绍两种不同的实现方法。1, 条件变量 view plaincopy to clipboardprint?102 import threading 103 104 import time 105 106 class Producer(threading.Thread): 107 108 def _init_(self, t_name): 109 110 threading.Thread._init_(self, name=t_name) 111 112 113 114 def run(self): 115 116 global x 117 118 con.acquire() 119 120 if x 0: 121 122 con.wait() 123 124 else: 125 126 for i in range(5): 127 128 x=x+1 129 130 print producing. + str(x) 131 132 con.notify() 133 134 print x 135 136 con.release() 137 138 139 140 class Consumer(threading.Thread): 141 142 def _init_(self, t_name): 143 144 threading.Thread._init_(self, name=t_name) 145 146 def run(self): 147 148 global x 149 150 con.acquire() 151 152 if x = 0: 153 154 print consumer wait1 155 156 con.wait() 157 158 else: 159 160 for i in range(5): 161 162 x=x-1 163 164 print consuming. + str(x) 165 166 con.notify() 167 168 print x 169 170 con.release() 171 172 173 174 con = threading.Condition() 175 176 x=0 177 178 print start consumer 179 180 c=Consumer(consumer) 181 182 print start producer 183 184 p=Producer(producer) 185 186 187 188 p.start() 189 190 c.start() 191 192 p.join() 193 194 c.join() 195 196 print x 上面的例子中,在初始状态下,Consumer处于wait状态,Producer连续生产(对x执行增1操作)5次后,notify正在等待的Consumer。Consumer被唤醒开始消费(对x执行减1操作) 2, 同步队列Python中的Queue对象也提供了对线程同步的支持。使用Queue对象可以实现多个生产者和多个消费者形成的FIFO的队列。生产者将数据依次存入队列,消费者依次从队列中取出数据。 view plaincopy to clipboardprint?197 # producer_consumer_queue 198 199 from Queue import Queue 200 201 import random 202 203 import threading 204 205 import time 206 207 208 209 #Producer thread 210 211 class Producer(threading.Thread): 212 213 def _init_(self, t_name, queue): 214 215 threading.Thread._init_(self, name=t_name) 216 217 self.data=queue 218 219 def run(self): 220 221 for i in range(5): 222 223 print %s: %s is producing %d to the queue!n %(time.ctime(), self.getName(), i) 224 225 self.data.put(i) 226 227 time.sleep(random.randrange(10)/5) 228 229 print %s: %s finished! %(time.ctime(), self.getName() 230 231 232 233 #Consumer thread 234 235 class Consumer(threading.Thread): 236 237 def _init_(self, t_name, queue): 238 239 threading.Thread._init_(self, name=t_name) 240 241 self.data=queue 242 243 def run(self): 244 245 for i in range(5): 246 247 val = self.data.get() 248 249 print %s: %s is consuming. %d in the queue is consumed!n %(time.ctime(), self.getName(), val) 250 251 time.sleep(random.randrange(10) 252 253 print %s: %s finished! %(time.ctime(), self.getName() 254 255 256 257 #Main thread 258 259 def main(): 260 261 queue = Queue() 262 263 producer = Producer(Pro., queue) 264 265 consumer = Consumer(Con., queue) 266 267 producer.start() 268 269 consumer.start() 270 271 producer.join() 272 273 consumer.join() 274 275 print All threads terminate! 276 277 278 279 if _name_ = _main_: 280 281 main() 在上面的例子中,Producer在随机的时间内生产一个“产品”,放入队列中。Consumer发现队列中有了“产品”,就去消费它。本例中,由于Producer生产的速度快于Consumer消费的速度,所以往往Producer生产好几个“产品”后,Consumer才消费一个产品。Queue模块实现了一个支持多producer和多consumer的FIFO队列。当共享信息需要安全的在多线程之间交换时,Queue非常有用。Queue的默认长度是无限的,但是可以设置其构造函数的maxsize参数来设定其长度。Queue的put方法在队尾插入,该方法的原型是:put( item, block, timeout)如果可选参数block为true并且timeout为None(缺省值),线程被block,直到队列空出一个数据单元。如果timeout大于0,在timeout的时间内,仍然没有可用的数据单元,Full exce
温馨提示
- 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
- 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
- 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
- 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
- 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
- 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
- 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
最新文档
- 2025年健康管理师中级考试模拟试题与备考策略指导
- 2025年产后恢复师职业发展中级面试要点及模拟题解析
- 大型体育设施施工安全文明施工保证措施
- 三年级语文下册课题复习解析计划
- 智慧城市项目勘察设计的进度保证措施
- 美业人进修专业知识培训课件
- 气道出血药物治疗方案
- 2025-2030中国游戏角色造型设计潮流与文化符号运用报告
- 部编版一年级道德与法治下册教学质量保障计划
- 某汽车配件电商店铺销售运营推广计划
- 驾驶员安全教育培训考试试卷含答案
- 污水处理站运行记录台账范本
- 2025年消毒供应室业务学习考试试题(附答案)
- 校园基孔肯雅热防控措施课件
- 图像特征提取讲解
- 多彩贵州地方课程课件
- 劳技自制收纳盒课件
- 《管理学基础与实务》 课件全套 曾宪达 第1-11章 管理与管理者- 管理创新
- 2025年复工复产考核试题及答案
- 快餐公司门店设备夜间关闭管理制度
- 【公路监理大纲】公路工程监理大纲(含桥隧工程)
评论
0/150
提交评论