十九.Python线程

Python线程

 #threading模块

import threading
#python 线程
#threading 线程模块 用于创建python并发程序
#threading.Thread(target=,args=)  创建一个线程程序

#threading类的函数
#threading.currentThread() #获取当前的线程实例
#threading.active_count() #获取当前该程序运行的线程数量
#threading.enumerate()    #获取当前运行的所有线程实例的list列表

#线程对象的函数
#thread.start()  #启动线程实例
#thread.run()    #线程实例运行
#thread.join()   #子线程未运行结束,阻塞主线程执行(主线程等待子线程)
#thread.is_alive() ##输出线程实例是否还在执行,执行返回True
#thread.isAlive()  #输出线程实例是否还在执行,执行返回True
#thread.setDaemon()  #将线程实例设置为守护进程,
#thread.isDaemon()  #输出该线程实例是否是守护进程
#thread.getName()   #输出该线程的线程名字
#thread.setName()   #设置该线程的线程名

import time
def hi(num):
    print("%s print %s begin at %s"%(threading.current_thread().getName(),num,time.ctime()))
    #执行打印,线程等待3秒,子线程结束
    time.sleep(3)
    print("%s end at %s"%(threading.current_thread().getName(),time.ctime()))
if __name__=="__main__":
    #创建线程1,参数是10
    t1=threading.Thread(target=hi,args=(10,))
    #创建线程2,参数是20
    t2=threading.Thread(target=hi,args=(20,))
    #启动线程,等待cpu执行
    t1.start()
    #启动线程,等待cpu执行
    t2.start()
    #打印所有正在运行的线程列表
    print(threading.enumerate())
    print("ending... at %s"%time.ctime())


import threading
import time
#join  主线程等待子线程
#thread.join()要在thread.start()之后调用
#thread.join()  该线程运行完毕,主线程在往下执行

def hi():
    print("%s start at %s"%(threading.current_thread().getName(),time.ctime()))
    #线程休眠3秒
    time.sleep(3)
    print("% send at %s" % (threading.current_thread().getName(), time.ctime()))
def hi1():
    print("%s start at %s"%(threading.current_thread().getName(),time.ctime()))
    #线程休眠5秒
    time.sleep(5)
    print("%s end at %s" % (threading.current_thread().getName(), time.ctime()))

#创建存储线程的list
threads=[]
if __name__=="__main__":
    #创建线程
    t1=threading.Thread(target=hi)
    t1.setName("3秒线程")
    t2=threading.Thread(target=hi1)
    t2.setName("5秒线程")
    #添加线程到list
    threads.append(t1)
    threads.append(t2)
    #循环list启动线程
    for i in threads:
        #启动线程
        i.start()
    #主线程等待子线程2运行完毕,主线程在往下执行
    t2.join()
    print("main__thread end....")
import threading
import time

#setDaemon() 将子线程设置为主线程的守护线程,如果主线程结束,守护子线程也跟着结束
#主线程不会等待守护线程,当除守护线程以外的所有线程结束,主线程也会结束,守护线程会跟随主线程一起结束
#thread.setDaemon()在thread.start()之前设置

def h1():
    print("%s start at %s"%(threading.current_thread().getName(),time.ctime()))
    time.sleep(3)
    print("%s end at %s"%(threading.current_thread().getName(),time.ctime()))
def h2():
    print("%s start at %s"%(threading.current_thread().getName(),time.ctime()))
    time.sleep(5)
    #该线程为守护线程,主线程会在3秒后停止,该线程会跟随主线程一起停止,所以下面不会打印
    print("%s end at %s"%(threading.current_thread().getName(),time.ctime()))

#创建线程列表
thread_list=[]

if __name__=="__main__":
    #创建线程
    t1=threading.Thread(target=h1)
    t2=threading.Thread(target=h2)
    #修改线程名字
    t1.setName("listening")
    t2.setName("reading")
    #设置t2为守护线程
    t2.setDaemon(True)
    #将线程加入到线程列表
    thread_list.append(t1)
    thread_list.append(t2)

    #循环线程列表启动线程
    for i in thread_list:
        #启动线程
        i.start()

    print("main_thread ending....")

 #Lock同步锁

#Lock 同步锁

import threading
#线程锁
#同步锁        一个方法只允许一个线程执行,可以使线程安全
#死锁         多个线程互相等待的现象叫做死锁现象
#递归锁       递归锁内置计数器,加锁计数器加1,释放锁计数器减1,当内置计数器大于0,为加锁状态,其他线程不允许访问此方法,
#              当计数器为0时,为锁的释放状态


# 同步锁
# lock=threading.Lock() 创建同步锁
# lock.acquire()  加锁
# lock.release()  释放锁

import time

a = 100


def add():
    # 为add函数加锁
    l.acquire()
    global a
    a -= 1
    time.sleep(0.1)
    # 函数运行完毕释放锁
    l.release()


# 线程列表
threads = []
if __name__ == "__main__":
    # 创建同步锁
    l = threading.Lock()
    # 循环创建100个线程
    for i in range(100):
        ab = threading.Thread(target=add)
        threads.append(ab)
    # 循环开启100个线程
    for i in threads:
        i.start()
    # 为线程添加主线程阻塞的join方法,让所有子线程运行完毕再打印a
    for i in threads:
        i.join()
    print(a)



 #同步引起的死锁问题

#死锁
import threading
import time
# 死锁  是两个线程未获取到同步锁互相等待的过程
#通过创造两个线程互相等待的状况,所有线程都会等待,出现卡死的现象,就是死锁现象
class tex:
    def __init__(self):
        pass
    def ActionA(self):
        #同步锁A加锁
        lockA.acquire()
        print("%s LockA ..." % threading.currentThread().getName())
        time.sleep(2)
        #同步锁B加锁
        lockB.acquire()
        print("%s LockB...." % threading.currentThread().getName())
        time.sleep(3)
        #同步锁A释放锁
        lockA.release()
        #同步锁B释放锁
        lockB.release()

    def ActionB(self):
        #同步锁B加锁
        lockB.acquire()
        print("%s LockB ..." % threading.currentThread().getName())
        time.sleep(2)
        #同步锁A加锁
        lockA.acquire()
        print("%s LockB...." % threading.currentThread().getName())
        time.sleep(3)
        #同步锁B释放锁
        lockB.release()
        #同步锁A释放锁
        lockA.release()

    def testAB(self):
        self.ActionA()
        self.ActionB()


#存储线程的列表
threads = []
if __name__ == "__main__":
    #创建线程锁lockA
    lockA = threading.Lock()
    #创建线程锁lockB
    lockB = threading.Lock()
    #循环创建100个线程
    for i in range(100):
        t = threading.Thread(target=tex().testAB)
        threads.append(t)
    #循环执行100个线程
    for i in threads:
        i.start()

 #Rlock() 递归锁

#递归锁
import threading
import time
#递归锁       递归锁内置计数器,加锁计数器加1,释放锁计数器减1,当内置计数器大于0,为加锁状态,其他线程不允许访问此方法,
#              当计数器为0时,为锁的释放状态
class tex:
    def __init__(self):
        pass
    def ActionA(self):
        #递归锁加锁
        RlockA.acquire()     #计数器+1  加锁状态  1
        print("%s Lock...ActionA" %threading.currentThread().getName())
        time.sleep(2)
        #递归锁加锁
        RlockA.acquire()    #计数器+1 加锁状态   2
        print("%s Lock....ActionA" %threading.currentThread().getName())
        time.sleep(3)
        #递归锁释放锁
        RlockA.release()    #计数器-1 加锁状态   1
        print("%s unLock....ActionA" %threading.currentThread().getName())
        #递归锁释放锁
        RlockA.release()    #计数器-1 释放锁状态  0
        print("%s unLock....ActionA" %threading.currentThread().getName())

    def ActionB(self):
        #递归锁加锁
        RlockA.acquire()    #计数器+1  加锁状态  1
        print("%s Lock... ActionB" % threading.currentThread().getName())
        time.sleep(2)
        #递归锁加锁
        RlockA.acquire()    #计数器+1  加锁状态  2
        print("%s Lock....ActionB" % threading.currentThread().getName())
        time.sleep(3)
        #递归锁释放锁
        RlockA.release()       #计数器-1  加锁状态  1
        print("%s unLock....ActionB" %threading.currentThread().getName())
        #递归锁释放锁
        RlockA.release()    #计数器-1  加锁状态  0
        print("%s unLock....ActionB" %threading.currentThread().getName())

    def testAB(self):
        self.ActionA()
        self.ActionB()


#存储线程的列表
threads = []
if __name__ == "__main__":
    #创建递归锁RlockA
    RlockA = threading.RLock()

    #循环创建100个线程
    for i in range(100):
        t = threading.Thread(target=tex().testAB)
        threads.append(t)
    #循环执行100个线程
    for i in threads:
        i.start()

 #Event() 同步条件

#同步条件 Event
import threading
import time

#event=threading.Event() 创建同步条件
#event.wait()   等待event.set()方法执行以后,解除等待状态
#event.set()    解除event的wait()等待状态
#event.clear()  清空event的event.set()状态,使event.wait()继续进入下一个等待状态

def Boss():
    print("Boss say:今天要加班到11点")
    #解除阻塞
    event.set()
    time.sleep(5)
    #阻塞
    event.clear()
    print("Boss say:11点了,可以下班了!")
    #清除阻塞
    event.set()
def worker():
    #等待
    event.wait()
    print("worker say:哎...命真苦啊!")
    #清除event.set()开始阻塞
    event.clear()
    #进入等待状态
    event.wait()
    print("worker say:欧耶!")

works=[]
if __name__=="__main__":
    #创建同步条件
    event=threading.Event()
    #创建Boss线程
    t1=threading.Thread(target=Boss)
    #创建worker线程
    t2 = threading.Thread(target=worker)
    #将Boss线程添加到线程列表
    works.append(t1)
    #将worker线程添加到线程列表
    works.append(t2)
    #循环线程列表开启所有线程
    for i in works:
        #开启线程
        i.start()

 #semaPhore() 信号量

#信号量
import threading
import time
#信号量  一个方法允许线程同时访问的数量
#sema=threading.semaphore(5)  创建同时5个线程访问的信号量锁
#sema.acquire()               信号量锁执行加一操作,当信号量锁加锁数量为5时,信号量锁不允许其他线程访问该方法
#sema.release()               信号量锁执行减一操作
def add():
    sema.acquire()
    print("%s  %s 访问了add方法"%(time.ctime(),threading.currentThread().getName()))
    time.sleep(2)
    sema.release()

threads=[]
if __name__=="__main__":
    #创建一次允许5个线程访问的信号量锁
    sema=threading.Semaphore(5)
    #循环创建100个线程
    for i in range(100):
        #创建add方法的线程
        t=threading.Thread(target=add)
        #将创建好的线程加入到线程列表中
        threads.append(t)
    #循环线程列表
    for i in threads:
        #启动线程
        i.start()

 #线程并发利器  queue  队列

#线程队列
import threading
import queue
#队列的三种类型
#queue.Queue() FIFO  先进先出的队列
#queue.LifoQueue()  LIFO  后进先出的队列
#queue.PriorityQueue() 优先级队列

#que.qsize()  返回队列数量

#que=queue.Queue() 创建队列
#queue  线程队列模块
#que.put() 将元素存入队列
#que.get() 从队列依此获取元素
#que.taskdone()  #当que.get()成功执行,发送信号
#que.join()     #阻塞线程向下执行,接收信号,接触阻塞状态
def FIFo_queue():
    que.put("123")
    que.put({"name":"tom"})
    que.put([1,2,3,4,5])
    for i in range(3):
        print(que.get())
def LIFO_queue():
    que.put("123")
    que.put({"name":"tom"})
    que.put([1,2,3,4,5])
    #当que.get()成功调用时,会向que.join()方法一个信号,使que.join()解除阻塞的状态,继续向下执行
    que.task_done()
    for i in range(3):
        print(que.get())

def Priority_queue():
    que.put([2,"1111"])
    que.put([3,"2222"])
    que.put([4,{"name":"tom"}])
    #获取对应优先级的队列
    print(que.get())
    print(que.get())
    print(que.get())

if __name__=="__main__":
    que=queue.Queue()
    LIFO_queue()
    #que.join()会阻塞向下执行,当que.join()收到que.task_done()的信号时,解除阻塞状态,线程继续往下执行
    que.join()
    print(5555)




猜你喜欢

转载自blog.csdn.net/qq_39663113/article/details/85852792