Table of Contents

Python多线程

当主进程结束的时候,如果还有附属的子线程没有结束,那么就会发生错误:
要么将子进程join到主线程,等待子进程结束后整个程序再结束
要么将子进程detch出去


线程

threading.Thread()

继承这个类,描述一个线程

threading.Lock()

保护一块内存区域

信号量

threading.Semaphore(size)

协调生产者和消费者的进度

示例代码

import threading
import random
import queue
import time
 
QueueMaxSize=int(10)
 
#有可能多个线程同时访问的内存区域
Q=queue.Queue(maxsize=QueueMaxSize)
#上锁保护特定的内存区域
Q_Lock=threading.Lock()
#两个信号量
Q_Semaphore_Add=threading.Semaphore(QueueMaxSize)
Q_Semaphore_Remove=threading.Semaphore(0)
 
#生产
def Add(value:int)->int:
    Q_Semaphore_Add.acquire()
    Q_Lock.acquire()
 
    Q.put(value)
    Result=Q.qsize()
 
    Q_Lock.release()
    Q_Semaphore_Remove.release()
 
    return Result
 
#消费
def Remove()->int:
    Q_Semaphore_Remove.acquire()
    Q_Lock.acquire()
 
    Q.get()
    Result=Q.qsize()
 
    Q_Lock.release()
    Q_Semaphore_Add.release()
 
    return Result
 
#生产线程
class threadAdd(threading.Thread):
    def __init__(self):
        #务必注意初始化父类
        super().__init__()
        self.m_shouldStop=False
        self.m_shouldStop_Lock=threading.Lock()
 
    def shouldStop(self,newVal=None):
        self.m_shouldStop_Lock.acquire()
 
        if not newVal is None:
            self.m_shouldStop=newVal
        Res=self.m_shouldStop
 
        self.m_shouldStop_Lock.release()
 
        return Res
 
    def run(self):
        while not self.shouldStop(None):
            time.sleep(random.random())
            print('Add One',Add(0))
 
#消费线程
class threadRemove(threading.Thread):
    def __init__(self):
        #务必注意初始化父类
        super().__init__()
        self.m_shouldStop=False
        self.m_shouldStop_Lock=threading.Lock()
 
    def shouldStop(self,newVal=None):
        self.m_shouldStop_Lock.acquire()
 
        if not newVal is None:
            self.m_shouldStop=newVal
        Res=self.m_shouldStop
 
        self.m_shouldStop_Lock.release()
 
        return Res
 
    def run(self):
        while not self.shouldStop(None):
            time.sleep(random.random())
            print('Remove One',Remove())
 
def main():
    AddThread=threadAdd()
    RemoveThread=threadRemove()
 
    #启动线程
    AddThread.start()
    RemoveThread.start()
 
    x=input()
    print('Shutting')
 
    #停止两个线程
 
    if AddThread.is_alive():
        AddThread.shouldStop(True)
        AddThread.join()
 
    if RemoveThread.is_alive():
        RemoveThread.shouldStop(True)
        Add(0)#保证安全? 还是有风险
        RemoveThread.join()
 
if __name__=='__main__':
    main()