首页 > 编程语言 > 详细

Python的麻烦的多线程

时间:2020-01-10 14:25:33      阅读:57      评论:0      收藏:0      [点我收藏+]

对于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) + "\t" + 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

Python的麻烦的多线程

原文:https://www.cnblogs.com/awrrays/p/12175799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!