Thread and shared lock

时间:2022-09-02 10:21:05

在看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')

Thread and shared lock

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')

Thread and shared lock

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

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

Thread and shared lock

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

Thread and shared lock

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

Thread and shared lock

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

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. java19

    1:异常(理解) (1)程序出现的不正常的情况. (2)异常的体系 Throwable |--Error 严重问题,我们不处理. |--Exception |--RuntimeException 运行 ...

  2. 浅谈js的事件冒泡机制

    很多人都听说过,js的事件冒泡机制,其实,这个说法还是比较生动形象的,就是一个水泡在水底下,冒泡到水面的过程. 那js的事件冒泡机制呢,就是一个DOM树,一级一级向上冒的过程,最终是到document ...

  3. 获取Ip地址

    public static string GetClientIPv4Address() { string ipv4 = String.Empty; foreach (IPAddress ip in D ...

  4. 004. Asp.Net Routing与MVC 之二: 请求如何激活Controller和Action

    上篇讲到 请求到达 MvcRouteHandler ,并且透过 IRouteHandler.GetHttpHandler 获取到了真正的处理程序 MvcHandler 这次我们看看,MvcHandle ...

  5. 今天修改bug基本完成

    今天修改bug基本完成 在修改bug过程中配到几个郁闷的问题,印象最深的两个1.检查出生日期或日期的合法性,引用的日历控件不能完全保证取到值时操作,现在突然想到或许我该仔细研究日历控件接口,在返回错误 ...

  6. Hibernate的五个主要接口

    Hibernate作为持久成中间件,它的具体实现对与上层调用是透明的,即上层通过接口来调用Hibernate的具体实现,所以对于入门级别的讨论来说,自然应该先从接口开始了.

  7. 【云计算 Hadoop】Hadoop 版本 生态圈 MapReduce模型

    忘的差不多了, 先补概念, 然后开始搭建集群实战 ... . 一 Hadoop版本 和 生态圈 1. Hadoop版本 (1) Apache Hadoop版本介绍 Apache的开源项目开发流程 : ...

  8. python 上台阶

    题目描述: 有一楼梯共m级,刚开始在第一级,若每次只能跨上一级或两级,要走上第m级,共有多少走法? 注:规定从一级到一级有0种走法 ''' 有一楼梯共m级,刚开始在第一级,若每次只能跨上一级或两级,要 ...

  9. 防抖debounce和节流throttle

    大纲 一.出现缘由 二.什么是防抖debounce和节流throttle 三.应用场景 3.1防抖 3.2节流 一.出现缘由 前端开发中,有一部分用户行为会频繁触发事件,而对于DOM操作,资源加载等耗 ...

  10. java的日期

    直接看例子: import java.text.DateFormatSymbols; import java.util.Calendar; import java.util.GregorianCale ...