龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > web编程 > python编程 >

Python多线程同步Lock、RLock、Semaphore、Event实例(2)

时间:2014-11-22 02:24来源:网络整理 作者:网络 点击:
分享到:
复制代码 代码如下: import logging import threading import time logging.basicConfig(level=logging.DEBUG, format="(%(threadName)-10s : %(message)s", ) def wait_for_event_timeout(e, t): """Wait t

复制代码 代码如下:

import logging
import threading
import time

logging.basicConfig(level=logging.DEBUG,
format="(%(threadName)-10s : %(message)s",
)

def wait_for_event_timeout(e, t):
    """Wait t seconds and then timeout"""
    while not e.isSet():
      logging.debug("wait_for_event_timeout starting")
      event_is_set = e.wait(t)
      logging.debug("event set: %s" % event_is_set)
    if event_is_set:
      logging.debug("processing event")
    else:
      logging.debug("doing other work")
     
e = threading.Event()
t2 = threading.Thread(name="nonblock",
target=wait_for_event_timeout,args=(e, 2))
t2.start()
logging.debug("Waiting before calling Event.set()")
time.sleep(7)
e.set()
logging.debug("Event is set")

运行结果:

三、其他

1) 线程局部变量

线程局部变量的值是跟线程相关的,区别与全局的变量。使用非常简单如下:

复制代码 代码如下:

mydata = threading.local()
mydata.x = 1

2)对Lock,semaphore,condition等使用with关键字代替手动调用acquire()和release()。

精彩图集

赞助商链接