#练习:线程等待 Event e.set() e.wait()
 
from threading import Thread, Lock
import threading
import time
 
def wait_for_event(e):
    #Wait for the event to be set before doing anything
    print 'wait_for_event: starting'
    e.wait() # 等待收到能执行信号,如果一直未收到将一直阻塞
    print 'wait_for_event: e.is_set()->', e.is_set()
 
def wait_for_event_timeout(e, t):
    #Wait t seconds and then timeout
    print 'wait_for_event_timeout: starting'
    e.wait(t)# 等待t秒超时,此时Event的状态仍未未设置
    print 'wait_for_event_timeout: e.is_set()->', e.is_set()
    e.set()# 设置Event的状态
 
if __name__ == '__main__':
    e = threading.Event()
    print "begin, e.is_set()", e.is_set()
    w1 = Thread(name = 'block', target = wait_for_event, args = (e,))
    w1.start()
 
    w2 = Thread(name = 'nonblock', target = wait_for_event_timeout, args = (e, 2))
    w2.start()
    print 'main: waiting before calling Event.set()'
    time.sleep(3)
    # e.set()
    print 'main: event is set'
 
 
#练习:condition 等待notify_all() notify()
import threading as tr
import time
def consumer(cond):
    with cond:
        print("consumer before wait")
        cond.wait() # 等待消费
        print("consumer after wait")
 
def producer(cond):
    with cond:
        print("producer before notifyAll")
        cond.notify_all() # 通知消费者可以消费了
        print("producer after notifyAll")
 
if __name__ == '__main__':   
    condition = tr.Condition()
 
    t1 = tr.Thread(name = "thread-1", target = consumer, args=(condition,))
    t2 = tr.Thread(name = "thread-2", target = consumer, args=(condition,))
    t3 = tr.Thread(name = "thread-3", target = producer, args=(condition,))
 
    t1.start()
    time.sleep(2)
    t2.start()
    time.sleep(2)
    t3.start()
 
 
 
#练习:线程队列 队列是一种数据结构
from threading import Thread
from Queue import Queue  
import random, time
 
# 储钱罐
def create(queue):  
    for i in [100, 50, 20, 10, 5, 1, 0.5]:
      if not queue.full():
        queue.put(i)  # 入队列
        print 'Put %sRMB to queue.' %i
        time.sleep(1)
 
# 取储钱罐中的零钱花
def get(queue):
  while 1:
    if not queue.empty():
      print 'Get %sRMB from queue.' %queue.get()
      time.sleep(2)
    else:
      break 
 
if __name__=="__main__":
    q = Queue() # 创建一个队列实例
    create_t = Thread(target = create, args = (q,))  
    get_t = Thread(target = get, args = (q,))  
    create_t.start() 
    #time.sleep(1) #这里稳妥起见,最好是sleep1秒
    get_t.start()
    create_t.join()
    get_t.join()
 
 
#练习:死锁 互相等,结果谁也等不到谁
 
import threading  
import time
 
#声明全局锁 不用global直接用
lock1 = threading.Lock()  
lock2 = threading.Lock()  
print lock1, lock2
class T1(threading.Thread):  
    def __init__(self, name):  
        threading.Thread.__init__(self)  
        self.t_name = name  
 
    def run(self):  
        lock1.acquire()  
        time.sleep(1)#睡眠的目的是让线程2获得调度,得到第二把锁
        print 'in thread T1',self.t_name
        time.sleep(2) 
        lock2.acquire() #线程1请求第二把锁
        print 'in lock l2 of T1'  
        lock2.release()      
        lock1.release() 
 
class T2(threading.Thread):  
    def __init__(self, name):  
        threading.Thread.__init__(self)  
        self.t_name = name  
 
    def run(self):  
        lock2.acquire()  
        time.sleep(2)#睡眠的目的是让线程1获得调度,得到第一把锁
        print 'in thread T2',self.t_name
        lock1.acquire() #线程2请求第一把锁
        print 'in lock l1 of T2'
        lock1.release() 
        lock2.release() 
 
def test():  
    thread1 = T1('A')  
    thread2 = T2('B')  
    thread1.start()  
    thread2.start()  
 
if __name__== '__main__':  
    test()

【Python】多线程-3的更多相关文章

  1. python多线程学习记录

    1.多线程的创建 import threading t = t.theading.Thread(target, args--) t.SetDeamon(True)//设置为守护进程 t.start() ...

  2. python多线程编程

    Python多线程编程中常用方法: 1.join()方法:如果一个线程或者在函数执行的过程中调用另一个线程,并且希望待其完成操作后才能执行,那么在调用线程的时就可以使用被调线程的join方法join( ...

  3. Python 多线程教程:并发与并行

    转载于: https://my.oschina.net/leejun2005/blog/398826 在批评Python的讨论中,常常说起Python多线程是多么的难用.还有人对 global int ...

  4. python多线程

    python多线程有两种用法,一种是在函数中使用,一种是放在类中使用 1.在函数中使用 定义空的线程列表 threads=[] 创建线程 t=threading.Thread(target=函数名,a ...

  5. python 多线程就这么简单(转)

    多线程和多进程是什么自行google补脑 对于python 多线程的理解,我花了很长时间,搜索的大部份文章都不够通俗易懂.所以,这里力图用简单的例子,让你对多线程有个初步的认识. 单线程 在好些年前的 ...

  6. python 多线程就这么简单(续)

    之前讲了多线程的一篇博客,感觉讲的意犹未尽,其实,多线程非常有意思.因为我们在使用电脑的过程中无时无刻都在多进程和多线程.我们可以接着之前的例子继续讲.请先看我的上一篇博客. python 多线程就这 ...

  7. python多线程监控指定目录

    import win32file import tempfile import threading import win32con import os dirs=["C:\\WINDOWS\ ...

  8. python多线程ssh爆破

    python多线程ssh爆破 Python 0x01.About 爆弱口令时候写的一个python小脚本,主要功能是实现使用字典多线程爆破ssh,支持ip表导入,字典数据导入. 主要使用到的是pyth ...

  9. 【python,threading】python多线程

    使用多线程的方式 1.  函数式:使用threading模块threading.Thread(e.g target name parameters) import time,threading def ...

  10. <转>Python 多线程的单cpu与cpu上的多线程的区别

    你对Python 多线程有所了解的话.那么你对python 多线程在单cpu意义上的多线程与多cpu上的多线程有着本质的区别,如果你对Python 多线程的相关知识想有更多的了解,你就可以浏览我们的文 ...

随机推荐

  1. sqlite3 新增数据

    cx = sqlite3.connect("c:/数据库名字")#打开数据库cu = cx.cursor()cu.execute("INSERT INTO [user] ...

  2. 不安装Oracle数据库使用plsqldevloper

    1.Oracle官网下载instantclient 解压到D:\zl\instantclient_11_2 2.配置环境变量 ORACLE_HOME = D:\zl\instantclient_11_ ...

  3. Windows下Python3.6安装第三方模块

    一 安装pip 一般需要用pip进行安装,不过我安装p3.6的时候pip已经有了. 如果没有的话,可以用在以下http://www.lfd.uci.edu/~gohlke/pythonlibs/#pi ...

  4. 【转】JavaScript => TypeScript 入门

    几个月前把 ES6 的特性都过了一遍,收获颇丰.现在继续来看看 TypesScript(下文简称为 “TS”).限于经验,本文一些总结如有不当,欢迎指正. 官网有这样一段描述: TypeScript ...

  5. Find a way out of the ClassLoader maze

    June 6, 2003 Q: When should I use Thread.getContextClassLoader() ? A: Although not frequently asked, ...

  6. PhpStudy的安装及使用教程

    1.PhpStudy是什么 phpstudy是一个PHP调试环境的程序集成包,phpStudy软件集成了最新的Apache.PHP.MySQL.phpMyAdmin.ZendOptimizer,一次性 ...

  7. -L、-rpath和-rpath-link的区别

    链接器ld的选项有 -L,-rpath 和 -rpath-link,看了下 man ld,大致是这个意思: -L::  “链接”的时候去找的目录,也就是所有的 -lFOO 选项里的库,都会先从 -L ...

  8. AI工具(星形工具)(光晕工具)(移动复制)(柜子绘制)5.12

    星形工具;基本操作与矩形一样,拖动星形工具绘制,点击键盘上箭头增加星形的角数.下箭头减少星形的角数. 选择星形工具在屏幕单击,出现星形对话框,可以设置半径1半径2,角点数.图中的星形就可以用星形工具绘 ...

  9. CAD绘制栏杆5.10

    REC绘制一个矩形,(40,40)回车.通过它的中点移动到扶手的中点用移动工具把它往右边稍微移动.在三维图中EXT命令拉伸它,拉到扶手底面.如图选择三维扶手,右击,加栏杆,选择我们绘制的栏杆,单元宽度 ...

  10. pycharm开发工具,使用

    在pycharm中,打的断点,仅在调试模式下,即debug 模式下,才有效 Use Alt + Shift + C to quickly review your recent changes to t ...