Day 30 process&thread_2
进程和线程_2
1、继承类创建线程
1 import threading,time 2 3 class Mythread(threading.Thread): #建立类,继承threading.Thread 4 def __init__(self): 5 threading.Thread.__init__(self) #继承父类的__init__功能 6 7 def run(self): #run为python 自带,后面实例化后,start()自动调用run()功能 8 print("{name} start to read in the {time}.".format(name=self,time = time.ctime())) 9 10 l = [] 11 for i in range(6): 12 t = Mythread() 13 t.start() #相当于t.run() 14 l.append(t) 15 t.join() 16 17 # for j in l: 18 # j.join() 19 20 print("All is end...{time}".format(time=time.ctime()))
2、互斥锁
1 import threading 2 import time 3 4 lock = threading.Lock() #引用互斥锁,使用前先定义 5 6 def sub(): 7 global num 8 lock.acquire() #lock.aquire() 引用锁后,只有运行到release()才能让其它单位继续引用 9 temp = num 10 time.sleep(0.1) 11 num = temp - 1 12 lock.release() #释放锁 13 time.sleep(2) 14 15 num = 100 16 l = [] 17 for i in range(100): 18 t = threading.Thread(target=sub,args=()) 19 t.start() 20 l.append(t) 21 22 for t in l: 23 t.join() 24 25 print(num)
3、递归锁和死锁
import threading,time Rlock = threading.RLock() #Rlock引入Lock和counter变量,每进行一次acquire,counter计数一次,release则减少一次,直到归0,其它线程才可以获得资源。 class Th(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): self.foo() self.bar() def foo(self): Rlock.acquire() print("I am %s GET LOCKA.....%s" %(self.name,time.ctime())) Rlock.acquire() print("I am %s GET LOCKB.....%s" %(self.name,time.ctime())) Rlock.release() Rlock.release() def bar(self): Rlock.acquire() print("I am %s GET LOCKA.....%s" %(self.name,time.ctime())) time.sleep(1) Rlock.acquire() print("I am %s GET LOCKB.....%s" %(self.name,time.ctime())) Rlock.release() Rlock.release() for i in range(10): t = Th() t.start()