多线程深入理解和守护线程、子线程、锁、queue、evenet等介绍

1、多线程类的继承

import threading
import time
class MyThreading(threading.Thread):
    def __init__(self,n):
        super(MyThreading,self).__init__()
        self.n = n
    def run(self):
        print("threading %s"%(self.n))
        time.sleep(2)


threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start()

E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
threading 2
。。。。。。。

2、线程测试案例

import threading
import time
class MyThreading(threading.Thread):
    def __init__(self,n):
        super(MyThreading,self).__init__()
        self.n = n
    def run(self):
        time.sleep(2)
        print("threading %s"%(self.n))



threading1 = MyThreading("%s" %(1))
threading2 = MyThreading("%s" %(2))
threading1.start()
threading1.join() ## 1执行完才会执行2
threading2.start()

print("main")

E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test4.py
threading 1
main
threading 2

3、多线程时间测试案例

import threading
import time
list = [ ]
def run(i):
    print("test %s"%(i))
    time.sleep(2)

starttime = time.time()
for i in range(1,50):
    t1 = threading.Thread(target=run,args=(i,))
    t1.start()
    list.append(t1)

for i in  list :
    i.join()

print("end")


endtime = time.time()
print("cost:", endtime-starttime)

E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
end
cost: 2.007871150970459

Process finished with exit code 0

 

 4、守护线程概念,默认情况下为非守护线程,即主线程推出前,需要等待所有的非守护线程结束放可以推出。而守护线程就表示这个线程“不重要”,即主线程结束时候,无需等待守护线程是否执行完成。

import threading
import time
list = [ ]
def run(i):
    print("test %s"%(i))
    time.sleep(5)
    print("setDaemon end ")

starttime = time.time()
for i in range(1,50):
    t1 = threading.Thread(target=run,args=(i,))
#    t1.setDaemon(True)
    t1.start()
    list.append(t1)


print("main  end")
E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main  end
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 
setDaemon end 

Process finished with exit code 0



import threading
import time
list = [ ]
def run(i):
    print("test %s"%(i))
    time.sleep(5)
    print("setDaemon end ")

starttime = time.time()
for i in range(1,50):
    t1 = threading.Thread(target=run,args=(i,))
    t1.setDaemon(True)
    t1.start()
    list.append(t1)


print("main  end")


E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/test3.py
test 1
test 2
test 3
test 4
test 5
test 6
test 7
test 8
test 9
test 10
test 11
test 12
test 13
test 14
test 15
test 16
test 17
test 18
test 19
test 20
test 21
test 22
test 23
test 24
test 25
test 26
test 27
test 28
test 29
test 30
test 31
test 32
test 33
test 34
test 35
test 36
test 37
test 38
test 39
test 40
test 41
test 42
test 43
test 44
test 45
test 46
test 47
test 48
test 49
main  end

Process finished with exit code 0

 5、GIL 和线程锁。GIL就是一把全局排他锁。他的作用就是保证同一时刻只有一个线程可以执行代码,对多线程有较大影响。

import threading
import time
lock  = threading.Lock()
list = [ ]

res = 0
def run(i):
    # 在Python3.5中已经优化,结果都是50.在python2.7如果不加锁可能有一场
    lock.acquire()
    global res
    res =  res + 1
    lock.release()


starttime = time.time()
for i in range(0,50):
    t1 = threading.Thread(target=run,args=(i,))
    t1.setDaemon(True)
    t1.start()
    list.append(t1)

for i in list:
    i.join()


print(res)

 6、当有多重锁时候,可以使用Rlock,使用递归锁可以避免出现死锁的情况

7、信号量简单实用。信号量就相当于多把锁

# Author : xiajinqi
import threading
import time

semaphore = threading.BoundedSemaphore(5)

def run(i):
    semaphore.acquire()
    print("阮娇。。。。")
    time.sleep(2)
    semaphore.release()

for i  in range(1,20):
    tt = threading.Thread(target=run,args=(i,))
    tt.start()

8、event 在线程间简单应用,车子等红灯

# Author : xiajinqi
import threading
import time

event = threading.Event()

# 0 -10 绿灯 10-20红灯,大于二十从0开始
def lighter():
    count = 0
    while  True :

        if count >= 10 and count <20 :
            event.clear()
            print("当前红灯")
            count = count + 1
        elif count >=20 :
            count = 0
        else :
            event.set()
            print("当前绿灯")
            count += 1
        time.sleep(1)
def run():
    while True :
        time.sleep(1)
        if event.is_set() : #event.waite(0 如果没有值,就会一直卡主等待
            print("开始过十字路口")
        else :
            print("开始等车")
            event.wait()



t1 = threading.Thread(target=lighter)
t2 = threading.Thread(target=run)

t1.start()
t2.start()

9、队列queue和列表、元组的区别。二者都有顺序。但是从列表取一个数据,数据还存在。而队列取出一个数据以后,改数据在队列就会被清空。符合实际应用场景。队列有三种:一、先进先去 二、先进后去 三、可以设置优先级别的队

import queue

# 先进先去
qu= queue.Queue()
for i in range(1,5):
    qu.put(i)

while qu.qsize() >0:
    print(qu.get())

# 先进后去
import queue

# 先进先去
qu= queue.LifoQueue()
for i in range(1,5):
    qu.put(i)

while qu.qsize() >0:
    print(qu.get())

E:\Users\xiajinqi\PycharmProjects\Atm\venv\Scripts\python.exe E:/Users/xiajinqi/PycharmProjects/Atm/333.py
4
3
2
1

import queue

# 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue()


list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")]


for lt in list:
    qq.put(lt)

while qq.qsize() >0:
    print(qq.get())

import queue

# 具有优先级别的队列 .类型需要一样
qq= queue.PriorityQueue()


list =[(1,"xiajinqi"),(1,"test"),(2,"test2"),(3,"test3"),(5,"test5"),(3,"test3")]


for lt in list:
    qq.put(lt)

while qq.qsize() >0:
    print(qq.get())

  

 

 

10、消费者生产者模型,解耦,相互不影响

import queue
import time
import threading
qu = queue.Queue(maxsize=10)





# 每次生产十个
def Producder():
    while True:
        for i  in range(1,3):
            print("生产了两个骨头")
            qu.put("骨头 %s"%(i))
        time.sleep(2)


# 生产者消费者模型,多个人生产多个人消费。
def Consumer(name) :
    while True:
        print("%s 吃了一个骨头 %s"%(name,qu.get()))
        time.sleep(0.5)


#两个消费
c1 = threading.Thread(target=Consumer,args=("test1",))
c2 = threading.Thread(target=Consumer,args=("test2",))
pd1 = threading.Thread(target=Producder)
pd1.start()
c1.start()
c2.start()

 

posted @ 2018-08-08 22:27  马里亚纳仰望星空  Views(325)  Comments(0Edit  收藏  举报