当出现竞态条件时候,即在同一个时刻只有一个线程可以进入临界区,需要使用同步。

常见的同步原语有两种:锁/互斥,信号量。

  锁是最简单,最低级的机制。

首先看一个不使用锁时候的多线程示例:

from atexit import register
from time import sleep, ctime
from threading import currentThread, Thread
from random import randrange class cleanOutput(list):
def __str__(self):
return ','.join(self) loops = [randrange(2, 5) for x in range(randrange(3, 7))]
remaining = cleanOutput() def loop(nsec):
myname = currentThread().name
remaining.append(myname)
print('{0} starting at {1}'.format(myname, ctime()))
sleep(nsec)
remaining.remove(myname)
print('{0} end at {1}'.format(myname, ctime()))
print('remaining {0}'.format(remaining)) def main():
for i in loops:
Thread(target=loop, args=(i,)).start() @register
def _atexit():
print("end!") if __name__ == '__main__':
main()

输出结果1:

Thread-1 starting at Tue Dec 20 23:12:03 2016
Thread-2 starting at Tue Dec 20 23:12:03 2016
Thread-3 starting at Tue Dec 20 23:12:03 2016
Thread-4 starting at Tue Dec 20 23:12:03 2016
Thread-5 starting at Tue Dec 20 23:12:03 2016
Thread-6 starting at Tue Dec 20 23:12:03 2016
Thread-2 end at Tue Dec 20 23:12:05 2016
Thread-3 end at Tue Dec 20 23:12:05 2016
Thread-5 end at Tue Dec 20 23:12:05 2016
remaining Thread-1,Thread-4,Thread-6
remaining Thread-1,Thread-4,Thread-6
remaining Thread-1,Thread-4,Thread-6
Thread-1 end at Tue Dec 20 23:12:06 2016
remaining Thread-4,Thread-6
Thread-6 end at Tue Dec 20 23:12:06 2016
remaining Thread-4
Thread-4 end at Tue Dec 20 23:12:06 2016
remaining
end!

输出结果2:

Thread-1 starting at Tue Dec 20 23:18:45 2016
Thread-2 starting at Tue Dec 20 23:18:45 2016
Thread-3 starting at Tue Dec 20 23:18:45 2016
Thread-4 starting at Tue Dec 20 23:18:45 2016
Thread-1 end at Tue Dec 20 23:18:47 2016
remaining Thread-2,Thread-3,Thread-4
Thread-3 end at Tue Dec 20 23:18:47 2016
Thread-2 end at Tue Dec 20 23:18:47 2016
remaining Thread-4
remaining Thread-4
Thread-4 end at Tue Dec 20 23:18:48 2016
remaining
end!

可以看到输出的结果非常奇怪,当多个线程同时使用remaining列表时候,结果会出现意外。

当使用锁时,即

 from atexit import register
from time import sleep, ctime
from threading import currentThread, Thread, Lock
from random import randrange class cleanOutput(list):
def __str__(self):
return ','.join(self) loops = [randrange(2, 5) for x in range(randrange(3, 7))]
remaining = cleanOutput()
lock = Lock() def loop(nsec):
myname = currentThread().name
with lock:          #也可以使用lock.acquire()和lock.release()
remaining.append(myname)          
print('{0} starting at {1}'.format(myname, ctime()))
sleep(nsec)
with lock:
remaining.remove(myname)
print('{0} end at {1}'.format(myname, ctime()))
print('remaining {0}'.format(remaining)) def main():
for i in loops:
Thread(target=loop, args=(i,)).start() @register
def _atexit():
print("end!") if __name__ == '__main__':
main()

输出结果为:

Thread-1 starting at Tue Dec 20 23:22:53 2016
Thread-2 starting at Tue Dec 20 23:22:53 2016
Thread-3 starting at Tue Dec 20 23:22:53 2016
Thread-4 starting at Tue Dec 20 23:22:53 2016
Thread-5 starting at Tue Dec 20 23:22:53 2016
Thread-6 starting at Tue Dec 20 23:22:53 2016
Thread-1 end at Tue Dec 20 23:22:55 2016
remaining Thread-2,Thread-3,Thread-4,Thread-5,Thread-6
Thread-4 end at Tue Dec 20 23:22:55 2016
remaining Thread-2,Thread-3,Thread-5,Thread-6
Thread-2 end at Tue Dec 20 23:22:55 2016
remaining Thread-3,Thread-5,Thread-6
Thread-5 end at Tue Dec 20 23:22:56 2016
remaining Thread-3,Thread-6
Thread-6 end at Tue Dec 20 23:22:57 2016
remaining Thread-3
Thread-3 end at Tue Dec 20 23:22:57 2016
remaining
end!

结果正常了

参考资料:Python核心编程.第四章.Wesley Chun著

【Python@Thread】锁示例的更多相关文章

  1. Python多线程锁

    [Python之旅]第六篇(四):Python多线程锁   python lock 多线程 多线程使用方法 多线程锁 摘要:   在多线程程序执行过程中,为什么需要给一些线程加锁以及如何加锁,下面就来 ...

  2. java使用zookeeper实现的分布式锁示例

    java使用zookeeper实现的分布式锁示例 作者: 字体:[增加 减小] 类型:转载 时间:2014-05-07我要评论 这篇文章主要介绍了java使用zookeeper实现的分布式锁示例,需要 ...

  3. TLS 与 python thread local

    TLS 先说TLS( Thread Local Storage),wiki上是这么解释的: Thread-local storage (TLS) is a computer programming m ...

  4. [译]Java Thread Sleep示例

    Java Thread Sleep示例 java.lang.Thread sleep(long millis)方法被用来暂停当前线程的执行,暂停时间由方法参数指定,单位为毫秒.注意参数不能为负数,否则 ...

  5. [译]Java Thread join示例与详解

    Java Thread join示例与详解 Java Thread join方法用来暂停当前线程直到join操作上的线程结束.java中有三个重载的join方法: public final void ...

  6. Boost::Thread使用示例 - CG-Animation - 博客频道 - CSDN.NET

    Boost::Thread使用示例 - CG-Animation - 博客频道 - CSDN.NET Boost::Thread使用示例 分类: C/C++ 2011-07-06 14:48 5926 ...

  7. Python Thrift 简单示例

    本文基于Thrift-0.10,使用Python实现服务器端,使用Java实现客户端,演示了Thrift RPC调用示例.Java客户端提供两个字符串参数,Python服务器端计算这两个字符串的相似度 ...

  8. python psutil简单示例

    python psutil简单示例 利用psutil编写简单的检测小脚本 0.安装psutil模块                                                    ...

  9. Python操作SQLServer示例(转)

    转自:http://www.cnblogs.com/lrzy/p/4346781.html 本文主要是Python操作SQLServer示例,包括执行查询及更新操作(写入中文). 需要注意的是:读取数 ...

  10. 转:Python操作SQLServer示例

    注:此文也是转载,2018年1月发现此文阅读量过万,略感不安.当时只是为了自己存档学习,未粘此文的原始连接.如有侵权,通过即删除,敬请谅解! 从网上找的,估计原文是:Python操作SQLServer ...

随机推荐

  1. cocos2d基本类介绍 director/scene/layer/sprite

    [核心类]     导演Director.场景Scene.布景层Layer.精灵Sprite的概念请移步:     导演控制场景,场景控制图层,图层控制精灵,精灵控制动作.     相互之间的关系框架 ...

  2. Python2 基于urllib2 的HTTP请求类

    一个利用urllib2模块编写的下载器,虽然有了requests模块,但是毕竟标准库 import urllib2,random class strong_down(): def __init__(s ...

  3. C# CodeHelper

    using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using Syste ...

  4. ubuntu 16.04安装mips交叉编译

    1. 在 /etc/apt/sources.list 文件末尾添加下面的更新源: deb http://ftp.de.debian.org/debian squeeze main deb http:/ ...

  5. HttpURLConnection传JSON数据

    try { //创建连接 URL url = new URL(url); HttpURLConnection connection = (HttpURLConnection) url.openConn ...

  6. 解码红外遥控信号——使用遥控器的按键来调节LED的亮度

    程序开始时,提示遥控键0~4的代码,然后程序通过设置LED的亮度来对被按下的按钮作出响应,以0关闭LED,1~4提供增加的亮度. 代码如下:(需要使用IRremote库,可在库管理中搜索该库进行下载后 ...

  7. css3 box-reflect 倒影效果

    语法: box-reflect:包括3个值. 1. direction 定义方向,取值包括 above . below . left . right. above: 指定倒影在对象的上边 below: ...

  8. JVM调优实战

      JVM调优实战 文档修订记录 版本 日期 撰写人 审核人 批准人 变更摘要 & 修订位置                                                   ...

  9. USACO 3.3 Shopping Offers

    Shopping OffersIOI'95 In a certain shop, each kind of product has an integer price. For example, the ...

  10. MFC多线程各种线程用法 .

    http://blog.csdn.net/qq61394323/article/details/9328301 一.问题的提出 编写一个耗时的单线程程序: 新建一个基于对话框的应用程序SingleTh ...