zoukankan      html  css  js  c++  java
  • Python的麻烦的多线程

    对于python的多线程,也就是threading模块,从开始学到现在,依旧觉得麻烦,对,依旧这么感觉。时隔已久,来整理一下。

     线程对象的方法:

    • Start() 开始线程的执行
    • Run() 定义线程的功能的函数
    • Join(timeout=None) 程序挂起,直到线程结束;如果给了timeout,则最多阻塞timeout秒
    • getName() 返回线程的名字
    • setName() 设置线程的名字
    • isAlive() 布尔标志,表示这个线程是否还在运行
    • isDaemon() 返回线程的daemon标志
    • setDaemon(daemonic) 把线程的daemon标志设为daemonic(一定要在start()函数前调用)
    • t.setDaemon(True) 把父线程设置为守护线程,当父进程结束时,子进程也结束。

    threading类的方法:

    • threading.enumerate() 正在运行的线程数量

     两种创建多线程的方式

    使用Thread()函数创建线程。

    import threading
    import time
    
    # 多线程A
    def fun(i):
        print(str(i) + "	" + time.strftime('%X'))
    
    for i in range(10):
        t = threading.Thread(target=fun, args=(i,))
        t.start()

    另一种通过继承threading类的方式,重写了run函数:

    import threading
    import time
    
    # 多线程B
    class myThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(self):
            try:
                print("success input " + time.strftime('%X'))
            except:
                pass
    
    
    for i in range(10):
        th = myThread()
        th.start()
    
    for i in range(10):
        th.join()

    多线程获取返回值

    python的多线程本身没有获取返回值的函数,继承threading类,然后写一个获取返回值的函数get_result。

    import threading
    import time
    
    # 多线程获取返回值
    class myThread(threading.Thread):
        def __init__(self, func, args=()):
            threading.Thread.__init__(self)
            self.func = func
            self.args = args
    
        def run(self):
            self.result = self.func(*self.args)
    
        def get_result(self):
            try:
                return self.result
            except Exception:
                pass
    
    
    def fun():
        return time.strftime('%Y-%m-%d %X')
    
    threads = []
    
    for i in range(20):
        t = myThread(fun)
        t.start()
        threads.append(t)
        
    for i in range(len(threads)):
        print(threads[i].get_result())
        threads[i].join()

    控制并发线程数的两种方法

    当执行任务特别多是,就需要控制并发线程数,threading类自带的方法。

    import threading
    import time
    
    # 控制线程数A
    thread_nums = 10
    
    set_thread_nums = threading.BoundedSemaphore(thread_nums)
    
    class myThread(threading.Thread):
        def __init__(self):
            threading.Thread.__init__(self)
    
        def run(self):
            set_thread_nums.acquire()
            try:
                a = 1
                print("The result is :{0} in {1}".format(a, time.strftime("%Y-%m-%d %X")))
                time.sleep(1)
            except:
                pass
            finally:
                set_thread_nums.release()
        
    
    for i in range(20):
        t = myThread()
        t.start()
    
    for i in range(20):
        t.join()

    也可以自己编写。

    import threading
    import time
    
    # 控制线程数B
    threads = []
    
    def fun():
        print(time.strftime("%Y-%m-%d %X"))
        time.sleep(1)
    
    for i in range(10):
        t = threading.Thread(target=fun)
        threads.append(t)
    
    for i in range(len(threads)):
        threads[i].start()
        while True:
            if len(threading.enumerate()) < 3:
                break
  • 相关阅读:
    wabpack 多页面 react配置 (对比单页面)
    vue-router+nginx非根路径的配置方法
    Vue-Devtools快速安装配置教程
    C++字符串
    NSIS插件制作
    HOOK学习
    排序:数组置顶元素(将数组某个元素排到第一位)
    raect hook中使用防抖(debounce)和节流(throttle)
    浏览器的缓存机制
    JavaScript踩坑解构赋值
  • 原文地址:https://www.cnblogs.com/awrrays/p/12175799.html
Copyright © 2011-2022 走看看