在看programing python 4th,第5张parallel system tool 192页开始,书中讲到thread知识,以下做个笔记,以便后期学习

1.主线程执行,开启5个子线程进行计数,没有使用mutex锁住,所以线程没有lock住资源,每个线程对全局变量的操作错乱,结果如下:

 """
synchronize access to stdout: because it is shared global
thread outputs may be intermixed if not syschronized
"""
import thread,time
global num #global var to be used by many threads
num=0 def cnt(id,count): # function run in threads
for i in range(count):
global num
#mutex.acquire() # lock the share var before execute
num +=1
time.sleep(0.5) # simulate read work
print('[%s] num= %s\n' %(id,num)) #print isn't interrupted now
#mutex.release() #release the lock for the other thread if __name__ =="__main__":
#mutex=thread.allocate_lock() #make a global mutex for lock
for i in range(5): #spawm 5 threads
thread.start_new_thread(cnt,(i,3)) #start threads
time.sleep(8) # wait for spawn thread work done,don't exit too early print('main thread exitting')

2.把mutex 注释打开,有了mutex变量,每一个线程进入都会独占num变量,结果如下:

 """
synchronize access to stdout: because it is shared global
thread outputs may be intermixed if not syschronized
"""
import thread,time
global num #global var to be used by many threads
num=0 def cnt(id,count): # function run in threads
for i in range(count):
global num
mutex.acquire() # lock the share var before execute
num +=1
time.sleep(0.5) # simulate read work
print('[%s] num= %s\n' %(id,num)) #print isn't interrupted now
mutex.release() #release the lock for the other thread if __name__ =="__main__":
mutex=thread.allocate_lock() #make a global mutex for lock
for i in range(5): #spawm 5 threads
thread.start_new_thread(cnt,(i,3)) #start threads
time.sleep(8) # wait for spawn thread work done,don't exit too early print('main thread exitting')

3.如果把time.sleep(6)注释掉或者子线程没有执行完毕,而主线程sleep的时间一到,主线程直接退出而不等待子线程执行完毕,结果如下:

a.主线程不等待,则直接退出

b.主线程只等待3s,而5个子线程需要7.5s,所以num只计数5.

4.设定有效等待时间和锁之后,主线程等待所有子线程执行结束才退出,结果如下:

6.无需在主线程设置等待时间,而是设定单独的锁或者变量来记录每个子线程的执行状态,每执行完一个线程,设定状态锁,然后在主线程判断所有状态锁的状态即可

 """
used mutexex to know when threads are done in parent/main thread,
instead of time.sleep;lock stdout to avoid comingled prints
"""
import thread,time
global num
num =0 def cnt(id,count):
for i in range(count):
global num
stdoutmutex.acquire()
num +=1
time.sleep(0.5)
print('[%s] num= %s time:[%s]\n' %(id,num,time.ctime())) #print isn't interrupted now
stdoutmutex.release()
#exitmutexs[id].acquire() # signal main thread
exitFlags[id] = True #signal main thread if __name__ =="__main__":
stdoutmutex = thread.allocate_lock() #make a global mutex for lock
#exitmutexs = [thread.allocate_lock() for i in range(5)]
exitFlags=[False]*5
for i in range(5): #spawm 5 threads
thread.start_new_thread(cnt,(i,3)) #start threads
#for mutex in exitmutexs:
# while not mutex.locked():
# pass
while False in exitFlags:pass
print('main thread exitting')

Thread and shared lock的更多相关文章

  1. Thread Based Parallelism - Thread Synchronization With Lock

    Thread Based Parallelism - Thread Synchronization With Lock import threading shared_resource_with_lo ...

  2. 深入理解Java并发框架AQS系列(四):共享锁(Shared Lock)

    深入理解Java并发框架AQS系列(一):线程 深入理解Java并发框架AQS系列(二):AQS框架简介及锁概念 深入理解Java并发框架AQS系列(三):独占锁(Exclusive Lock) 深入 ...

  3. Java Concurrency In Practice -Chapter 2 Thread Safety

    Writing thread-safe code is managing access to state and in particular to shared, mutable state. Obj ...

  4. How to Analyze Java Thread Dumps--reference

    原文地址:http://architects.dzone.com/articles/how-analyze-java-thread-dumps The Performance Zone is pres ...

  5. Thread in Java

    References: [1]. http://www.javaworld.com/article/2074481/java-concurrency/java-101--understanding-j ...

  6. How to Analyze Java Thread Dumps

    When there is an obstacle, or when a Java based Web application is running much slower than expected ...

  7. Do waiting or suspended tasks tie up a worker thread?

      https://blogs.msdn.microsoft.com/askjay/2012/07/29/do-waiting-or-suspended-tasks-tie-up-a-worker-t ...

  8. Android Process & Thread

    Native Service and Android Service Native Service:In every main() method of NativeService, which is ...

  9. PatentTips - Managing sequenced lock requests

    BACKGROUND In a multi-threaded processing environment, two or more threads may require access to a c ...

随机推荐

  1. PHP的排序算法跟查找算法

    排序算法: (1)冒泡排序 $arr = array(15,8,20,50,37,85,10,5,11,4); //冒泡排序 function maoPao($arr){ for($i = 0; $i ...

  2. NOI 题库 7624

    7624  山区建小学 描述 政府在某山区修建了一条道路,恰好穿越总共m个村庄的每个村庄一次,没有回路或交叉,任意两个村庄只能通过这条路来往.已知任意两个相邻的村庄之间的距离为di(为正整数),其中, ...

  3. 【DP】POJ 2385

    题意:又是Bessie 这头牛在折腾,这回他喜欢吃苹果,于是在两棵苹果树下等着接苹果,但苹果不能落地后再接,吃的时间不算,假设他能拿得下所有苹果,但是这头牛太懒了[POJ另一道题目说它是头勤奋的奶牛, ...

  4. openx中如何使用site-variable(参数)限制(关键词)广告显示

    openx是个很强大的广告管理系统,可以根据不同的情况显示不同的广告.其中可以根据get参数值的不同来显示,即delivery limitation中的site-variable选项,name表示变量 ...

  5. ios7迎来完美越狱,果粉狂欢!

    [我要]最近一则iOS7可以完美越狱的消息,可是乐坏了期待已久的果粉们.据科技博客网站Gizmodo报道,越狱专家Evasi0n团队最近攻破苹果的 iOS7系统,赶在圣诞前发布了iOS7的越狱.消息一 ...

  6. 事后分析报告(Postmortem Report)

    小组讨论照片 设想和目标 1.我们的团队项目为英语单词学习助手,名为“我爱记单词”.主要提供服务包括:单词查询,单词测试,单词记忆和中英互译.目前开发的是单机版本,用户可以根据自己的需求灵活的使用相应 ...

  7. Heartbeat+DRBD+MySQL高可用方案

    1.方案简介 本方案采用Heartbeat双机热备软件来保证数据库的高稳定性和连续性,数据的一致性由DRBD这个工具来保证.默认情况下只有一台mysql在工作,当主mysql服务器出现问题后,系统将自 ...

  8. GIT如何添加权限模块

    http://blog.chinaunix.net/uid-15174104-id-3843570.html

  9. iOS相关笔记

    #协议[1] [2] @property (nonatomic, assign) id<EveryFrameDelegate> delegate; 表明,这个delegate是一个需要实现 ...

  10. 数据库访问CRUD;__SELF__和__ACTION__的区别;自动收集表单:$n->create();

    一.tp框架数据访问(pdo基础) public function test() { $n = D("Nation"); //select();find(); //查询 1.$at ...