threading模塊 threading.Thread(target = func,argc = (arg1,arg2,)[,name=""]) 參數必須是元祖類型 threading.start()/threading.join([timeout=None]) 程式開始/掛起,直到結束 [+]s ...
threading模塊
import threading
import time
threading.Thread(target = func,argc = (arg1,arg2,)[,name=""])
參數必須是元祖類型
threading.start()/threading.join([timeout=None])
程式開始/掛起,直到結束
def sum(n):
sum = 0
for i in range(1,n+1):
sum+=i
time.sleep(0.001)
print(sum)
print('[+]single thread')
time1 = time.time()
sum(100);sum(100);
interval = time.time()-time1
print(' use:',interval)
print('[+]multithread')
n = [100,100]
my_thread = []
time2 = time.time()
for i in range(len(n)):
t = threading.Thread(target=sum,args=(n[i],))
my_thread.append(t)
for i in range(len(n)):
my_thread[i].start()
for i in range(len(n)):
my_thread[i].join()
interval = time.time()-time2
print(' use:',interval)
[+]single thread
5050
5050
use: 0.4396963119506836
[+]multithread
5050
5050
use: 0.2286393642425537
類思想重寫
繼承+重寫RUN函數
class myThread(threading.Thread):
def __init__(self,fun,args):
threading.Thread.__init__(self)
self.fun = fun
self.args = args
def run(self):
#print(self.args)
self.fun(self.args[0])
def sum(n):
sum = 0
for i in range(1,n+1):
sum+=i
time.sleep(0.001)
print(sum)
print('[+]single thread')
time1 = time.time()
sum(100);sum(100);
interval = time.time()-time1
print(' use:',interval)
print('[+]multithread')
n = [100,100]
my_thread = []
time2 = time.time()
for i in range(len(n)):
t = myThread(sum,(n[i],))
my_thread.append(t)
for i in range(len(n)):
my_thread[i].start()
for i in range(len(n)):
my_thread[i].join()
interval = time.time()-time2
print(' use:',interval)
[+]single thread
5050
5050
use: 0.38095712661743164
[+]multithread
5050
5050 use:
0.20025062561035156
Lock全局鎖
threading.Lock()
鎖標誌
lock.acquire()
獲得鎖標誌,返回bool
lock.release()
釋放鎖標誌
#不加鎖
class myThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global n
print("Thread:",n)
n += 1
n=0
t = []
for i in range(10):
t.append(myThread())
for i in range(10):
t[i].start()
for i in range(10):
t[i].join()
Thread:Thread: 1
0
Thread: 2
Thread: Thread:3 Thread:Thread:Thread:Thread:
4 Thread:
4678 9
#加鎖
class myThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
global n
if lock.acquire():
print("Thread:",n)
n += 1
lock.release()
else:
print('ERROR')
n=0
t = []
lock = threading.Lock()
for i in range(10):
t.append(myThread())
for i in range(10):
t[i].start()
for i in range(10):
t[i].join()