import random, threading
def threadFunction():
for i in range(10):
print 'ThreadFuction - %d'%i
time.sleep(random.randrange(0,2))
class ThreadClass(threading.Thread):
def __init__(self):
threading.Thread.__init__(self);
def run(self):
for i in range(10):
print 'ThreadClass - %d'%i
time.sleep(random.randrange(0,2))
if __name__ == '__main__':
tFunc = threading.Thread(target = threadFunction);
tCls = ThreadClass()
tFunc.start()
tCls.start()
ThreadFuction - 0 ThreadFuction - 1 ThreadFuction - 2 ThreadClass - 0 ThreadFuction - 3 ThreadClass - 1 ThreadFuction - 4 ThreadClass - 2 ThreadClass - 3 ThreadClass - 4ThreadFuction - 5 ThreadClass - 5 ThreadClass - 6 ThreadClass - 7 ThreadClass - 8 ThreadFuction - 6ThreadClass - 9 ThreadFuction - 7 ThreadFuction - 8 ThreadFuction - 9
class threading.Thread(group=None, target=None, name=None, args=(), kwargs={})
data = threading.local() def threadFunction(): global data data.x = 3 print threading.currentThread(), data.x if __name__ == '__main__': data.x = 1 tFunc = threading.Thread(target = threadFunction).start(); time.sleep(1) print threading.current_thread(), data.x
<Thread(Thread-1, started 36208)> 3 <_MainThread(MainThread, started 35888)> 1
def threadFunction(arg):
while True:
lock.acquire()
print 'ThreadFuction - %d'%arg
lock.release()
if __name__ == '__main__':
lock = threading.Lock()
threading.Thread(target = threadFunction, args=(1,)).start();
threading.Thread(target = threadFunction, args=(2,)).start();
threading.Condition([lock]) 分配一个条件变量
acquire(*args) 条件变量上锁
release() 条件变量解锁
wait([timeout]) 等待唤醒,timeout表示超时
notify(n=1) 唤醒最大n个等待的线程
notifyAll()、notify_all() 唤醒所有等待的线程
下面这个例子使用条件变量来控制两个线程交替运行
num = 0
def threadFunction(arg):
global num
while num < 10:
cond.acquire()
while num % 2 != arg:
cond.wait()
print 'Thread %d - %d' %(arg, num)
num += 1
cond.notify()
cond.release()
if __name__ == '__main__':
cond = threading.Condition()
threading.Thread(target = threadFunction, args=(0,)).start();
threading.Thread(target = threadFunction, args=(1,)).start();
Thread 0 - 0 Thread 1 - 1 Thread 0 - 2 Thread 1 - 3 Thread 0 - 4 Thread 1 - 5 Thread 0 - 6 Thread 1 - 7 Thread 0 - 8 Thread 1 - 9 Thread 0 - 10
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有