Skip to content

Instantly share code, notes, and snippets.

@manxisuo
Last active August 29, 2015 14:22
Show Gist options
  • Save manxisuo/59495c74938cf9170ce4 to your computer and use it in GitHub Desktop.
Save manxisuo/59495c74938cf9170ce4 to your computer and use it in GitHub Desktop.
Python Thread学习 (http://is.gd/kLyISF)
# encoding: UTF-8
import _thread as thread, time
import threading
# 一个用于在线程中执行的函数
def func():
for i in range(5):
print('func')
time.sleep(1)
# 结束当前线程
# 这个方法与thread.exit_thread()等价
# 当func返回时,线程同样会结束
thread.exit()
# 启动一个线程,线程立即开始运行
# 这个方法与thread.start_new_thread()等价
# 第一个参数是方法,第二个参数是方法的参数
thread.start_new(func, ())
# 创建一个锁(LockType,不能直接实例化)
# 这个方法与thread.allocate_lock()等价
lock = thread.allocate()
# 判断锁是锁定状态还是释放状态
print(lock.locked())
# 锁通常用于控制对共享资源的访问
count = 0
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
if lock.acquire():
count += 1
# 释放锁
lock.release()
# thread模块提供的线程都将在主线程结束后同时结束
time.sleep(6)
print('main thread exit')
# encoding: UTF-8
import threading
# 方法1:将要执行的方法作为参数传给Thread的构造方法
def func():
print('func() passed to Thread')
t = threading.Thread(target = func)
t.start()
# 方法2:从Thread继承,并重写run()
class MyThread(threading.Thread):
def run(self):
print('MyThread extended from Thread')
t = MyThread()
t.start()
# encoding: UTF-8
import threading
import time
def context(tJoin):
print('in threadContext.')
tJoin.start()
# 将阻塞tContext直到threadJoin终止。
tJoin.join()
# tJoin终止后继续执行。
print('out threadContext.')
def join():
print('in threadJoin.')
time.sleep(1)
print('out threadJoin.')
tJoin = threading.Thread(target=join)
tContext = threading.Thread(target=context, args=(tJoin,))
tContext.start()
# encoding: UTF-8
import threading, time
data = 0
lock = threading.Lock()
def func():
global data
print('%s acquire lock...' % threading.currentThread().getName())
# 调用acquire([timeout])时,线程将一直阻塞,
# 直到获得锁定或者直到timeout秒后(timeout参数可选)。
# 返回是否获得锁。
if lock.acquire():
print('%s get the lock.' % threading.currentThread().getName())
data += 1
time.sleep(2)
print('%s release lock...' % threading.currentThread().getName())
# 调用release()将释放锁。
lock.release()
t1 = threading.Thread(target = func)
t2 = threading.Thread(target = func)
t3 = threading.Thread(target = func)
t1.start()
t2.start()
t3.start()
# encoding: UTF-8
import threading
import time
rlock = threading.RLock()
def func():
threadName = threading.currentThread().getName()
# 第一次请求锁定
print('%s acquire lock...' % threadName)
if rlock.acquire():
print('%s get the lock.' % threadName)
time.sleep(2)
# 第二次请求锁定
print('%s acquire lock again...' % threadName)
if rlock.acquire():
print('%s get the lock.' % threadName)
time.sleep(2)
# 第一次释放锁
print('%s release lock...' % threadName)
rlock.release()
time.sleep(2)
# 第二次释放锁
print('%s release lock...' % threadName)
rlock.release()
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t3 = threading.Thread(target=func)
t1.start()
t2.start()
t3.start()
# encoding: UTF-8
import threading, time
# 商品
product = None
# 条件变量
con = threading.Condition()
# 生产者方法
def produce():
global product
if con.acquire():
while True:
if product is None:
print('produce...')
product = 'anything'
# 通知消费者,商品已经生产
con.notify()
# 等待通知
con.wait()
time.sleep(1)
# 消费者方法
def consume():
global product
if con.acquire():
while True:
if product is not None:
print('consume...')
product = None
# 通知生产者,商品已经没了
con.notify()
# 等待通知
con.wait()
time.sleep(1)
t1 = threading.Thread(target = produce)
t2 = threading.Thread(target = consume)
t2.start()
t1.start()
# encoding: UTF-8
import threading, time
# 计数器初值为2
semaphore = threading.Semaphore(2)
def func():
# 请求Semaphore,成功后计数器-1;计数器为0时阻塞
print('%s acquire semaphore...' % threading.currentThread().getName())
if semaphore.acquire():
print('%s get semaphore' % threading.currentThread().getName())
time.sleep(4)
# 释放Semaphore,计数器+1
print('%s release semaphore' % threading.currentThread().getName())
semaphore.release()
t1 = threading.Thread(target = func)
t2 = threading.Thread(target = func)
t3 = threading.Thread(target = func)
t4 = threading.Thread(target = func)
t1.start()
t2.start()
t3.start()
t4.start()
time.sleep(2)
# 没有获得semaphore的主线程也可以调用release
# 若使用BoundedSemaphore,t4释放semaphore时将抛出异常
print('MainThread release semaphore without acquire')
semaphore.release()
# encoding: UTF-8
import threading, time
event = threading.Event()
def func():
# 等待事件,进入等待阻塞状态
print('%s wait for event...' % threading.currentThread().getName())
event.wait()
# 收到事件后进入运行状态
print('%s receive event...' % threading.currentThread().getName())
t1 = threading.Thread(target=func)
t2 = threading.Thread(target=func)
t1.start()
t2.start()
time.sleep(2)
# 发送事件通知
print('MainThread set event.')
event.set()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment