python之threading模块
1、threading简介
2、创建线程
2.1、创建2个线程
import threading def run(n): print("task", n) t1 = threading.Thread(target=run, args=("t1",)) t2 = threading.Thread(target=run, args=("t2",)) t1.start() t2.start()
2.2、创建多个线程
import threading import time def run(n): print("task", n) time.sleep(2) print("task done", n) start_time = time.time() t_objs = [] # 存线程实例 for i in range(50): t = threading.Thread(target=run, args=("t-%s" % i,)) t.start() t_objs.append(t) # 为了不阻塞后面线程的启动,不在这里join,先放到一个列表里 for t in t_objs: # 循环线程实例列表,等待所有线程执行完毕 t.join() print("active count:",threading.activeCount()) print("----------all threads has finished...", threading.active_count()) # print("----------all threads has finished...", threading.activeCount())
2.3、使用线程锁
import threading import time def run(n): lock.acquire() global num num +=1 lock.release() lock = threading.Lock() num = 0 t_objs = [] #存线程实例 for i in range(10000): t = threading.Thread(target=run,args=("t-%s" %i ,)) t.start() t_objs.append(t) #为了不阻塞后面线程的启动,不在这里join,先放到一个列表里 for t in t_objs: #循环线程实例列表,等待所有线程执行完毕 t.join() print("----------all threads has finished...",threading.current_thread(),threading.active_count()) print("num:",num)