#!usr/bin/env python# -*- coding:utf-8 -*- __author__ = "Samson" import threading,timedef run(n): print("task", n) time.sleep(2) print("current thread:",threading.current_thread())#当前线程 t_obj = []#存线程实例start_time = time.time()for i in range(50): t = threading.Thread(target=run,args=("t%s" %i,)) #t.setDaemon(True)#把当前线程设置为守护线程,必须在t.start()之前设置,作用为主线程将不会等待该子线程结束 t.start() t_obj.append(t)print("total thread:",threading.active_count())#总线程数for t in t_obj: t.join()#等待线程执行完print("%s" %(abs(start_time-time.time()))) 多线程锁
#!usr/bin/env python# -*- coding:utf-8 -*- __author__ = "Samson" import threading,timedef run(n): lock.acquire()#锁上 global num num += 1 #time.sleep(1)#会变为单线程 lock.release()#解锁lock = threading.Lock()#创建锁num = 0t_obj = []#存线程实例for i in range(50): t = threading.Thread(target=run,args=("t%s" %i,)) t.start() t_obj.append(t)for t in t_obj: t.join()print("%s" %num)
多线程递归锁
#!usr/bin/env python# -*- coding:utf-8 -*- __author__ = "Samson" import threading,timedef run(): lock.acquire()#锁上 res = run1() res2 = run2() lock.release()#解锁def run1(): lock.acquire()#锁上 global num num += 1 lock.release()#解锁def run2(): lock.acquire()#锁上 global num num += 1 lock.release()#解锁lock = threading.RLock()#创建递归锁num = 0for i in range(10): t = threading.Thread(target=run) t.start()print("Now:",threading.active_count())while threading.active_count() != 1: print(threading.active_count())else: print("%s" %num)
原文地址:https://www.cnblogs.com/cansun/p/8379709.html
时间: 2024-11-07 23:21:32