标签:
Threading用于提供线程相关的操作,线程是应用程序中工作的最小单元。
#coding:utf-8 import threading import time def run(num): print("thread...",num) time.sleep(1) for i in range(10): #开通10个线程 t = threading.Thread(target=run,args=(i,)) #创建实例 t.start()
上述代码创建了10个“前台”线程,然后控制器就交给了CPU,CPU根据指定算法进行调度,分片执行指令。
更多方法:
import threading import time class MyThread(threading.Thread): def __init__(self,num): threading.Thread.__init__(self) self.num = num def run(self):#定义每个线程要运行的函数 print("running on number:%s" %self.num) time.sleep(3) if __name__ == ‘__main__‘: t1 = MyThread(1) t2 = MyThread(2) t1.start() t2.start()
线程锁(Lock、RLock)
由于线程之间是进行随机调度,并且每个线程可能只执行n条执行之后,当多个线程同时修改同一条数据时可能会出现脏数据,所以,出现了线程锁 - 同一时刻允许一个线程执行操作。
简单例子:
#coding:utf-8 import threading import time lock = threading.RLock() #创建个锁的实例 def run(num): lock.acquire() #对以下步骤(显示屏幕动作)线程进行锁住(让步骤有个串联执行顺序) print("thread...",num) lock.release() #解锁 time.sleep(1) #lock.release() for i in range(10): #开通10个线程 t = threading.Thread(target=run,args=(i,)) #创建实例 t.start()
例子:
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time gl_num = 0 def show(arg): global gl_num time.sleep(1) gl_num +=1 print gl_num for i in range(10): t = threading.Thread(target=show, args=(i,)) t.start() print ‘main thread stop‘
#!/usr/bin/env python #coding:utf-8 import threading import time gl_num = 0 lock = threading.RLock() def Func(): lock.acquire() global gl_num gl_num +=1 time.sleep(1) print gl_num lock.release() for i in range(10): t = threading.Thread(target=Func) t.start()
BoundedSemaphore:
#coding:utf-8 import threading import time #lock = threading.RLock() #创建个锁的实例 def run(num): sp.acquire() #对以下步骤(显示屏幕动作)线程进行锁住(让步骤有个串联执行顺序) print("thread...",num) print ‘‘ #lock.release() #解锁 time.sleep(1) sp.release() if __name__ == ‘__main__‘: sp = threading.BoundedSemaphore(3) #控制每个锁每次可以执行多少个线程 for i in range(12): #开通10个线程 t = threading.Thread(target=run,args=(i,)) #创建实例 t.start() while threading.activeCount() !=1: #当执行完所有动作后线程数默认有一个主线程 pass else: print ‘--------all threads are finish! ----------‘
标签:
原文地址:http://www.cnblogs.com/fengzaoye/p/5822442.html