Python学習ノート-Python threadingモジュール

16070 ワード

Python threadingモジュール
ダイレクトコール
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time

def sayhi(num):
    print("running on number:%s" % num)
    time.sleep(3)

if __name__ =='__main__':

    #        
     t1 = threading.Thread(target=sayhi,args=(1,))
     t2 = threading .Thread(target = sayhi,args=(2,))

     #      
     t1.start()
     t2.start()

    #     
     print(t1.getName())
     print(t2.getName())

呼び出しの継承
 
import threading
import time
class MyThread(threading.Thread):
    def __init__(self,num):
        # super(Mythread,self).__init__(self)
        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()

マルチスレッドおよび待機の一括処理
import threading
import time

def sayhi(num):

        print('running on number%s' %num)
        time.sleep(5)

if __name__ == '__main__':
    '''
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()
    '''
t_list=[] #      
for i in range(100):
  t = threading.Thread(target=sayhi,args =[i,] ) #      
  t.start()
  t_list.append(t) #           
for i in t_list:#           
    i.join() #           
print('##############main###############')

 
デーモンスレッド(Daemon)
import threading
import time

def run(n):
    print('--------runnig----------')
    time.sleep(200)
    print('--------done------------')

def main(self):
    for i in range(5):
        t = threading.Thread(target=run,args=[i,])
        t.start()
        t.join()
        print('start thread',t.getName())
m = threading.Thread(target=main,args=[])
m.setDaemon(True)#       Daemon  ,    ,          ,         
m.start()
print('-----main thread done-----')

 
スレッドロック
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import time
def addNum():
    global num #               
    print('----get num:%s' %num)
    time.sleep(2)
    lock.acquire()#       
    num-=1
    lock.release()#      

num = 100
thread_list=[]
lock = threading.Lock() #     
for i in range(100):
    t=threading.Thread(target=addNum)
    t.start()
    thread_list.append(t)

for t in thread_list:
    t.join() #          

print('final Num:%s'%num)

 
再帰ロック(RLock)
# !/usr/bin/env python
# -*- coding:utf-8 -*-
import threading,time

def run1():
    print("grab the first part data")
    lock.acquire()
    global num
    num +=1
    lock.release()
    return num
def run2():
    print("grab the second part data")
    lock.acquire()
    global  num2
    num2+=1
    lock.release()
    return num2
def run3():
    lock.acquire()#    
    res = run1() #  run1  
    print('--------between run1 and run2-----')
    res2 = run2()#  run2  
    lock.release()#     
    print(res,res2)


if __name__ == '__main__':

    num,num2 = 0,0 #     
    lock = threading.RLock()#     
    for i in range(10):
        t = threading.Thread(target=run3) #    
        t.start()

while threading.active_count() != 1:#          
    print(threading.active_count())
else:
    print('----all threads done---')
    print(num,num2)

Semaphore
反発ロックは同時に1つのスレッドのみがデータを変更することを許可し、Semaphoreは同時に一定数のスレッドがデータを変更することを許可する.
# !/usr/bin/env python
# -*- coding:utf-8 -*-

import threading,time

def run(n):
    semaphore.acquire()
    time.sleep(1)
    print("run the thread: %s
" %n) semaphore.release() if __name__ == '__main__': num= 0 semaphore = threading.BoundedSemaphore(3) # 5 for i in range(20): t = threading.Thread(target=run,args=(i,)) t.start() while threading.active_count() != 1: pass #print threading.active_count() else: print('----all threads done---') print(num)