小资料工程师乐园

python: 多线程threading模块

2020-06-29  本文已影响0人  luffynoonepiece

python的多线程模块threading基本使用介绍

import threading

threading模块的Thread类是核心,用于创建 thread对象

关键语句为:
#Target是最重要的参数,此处将一个callable对象(函数)赋值给Target
thread = threading.Thread(target = test)
thread.start()

有两种方式使用threading模块

1.面向过程

以下sample code有介绍daemon,join(),is_alive()等参数和方法

import threading
#threading.current_thread()方法可以返回线程本身,访问它的name属性
def test():
    for i in range(5):
        print(threading.current_thread().name,i)
        print(thread.is_alive())

#MainThread 结束,子线程也立马结束 ==> 在子线程的构造器中传递 daemon 的值为 True
thread = threading.Thread(target=test,daemon = False)
thread.start()
# Thread 的 is_alive() 方法查询线程是否还在运行。
#print(thread.is_alive())
# Thread 的 join() 方法,可以阻塞自身所在的线程。
#thread.join()

for i in range(5):
    print(threading.current_thread().name,i)

执行结果

Thread-1 0
MainThread 0
True
MainThread 1
Thread-1 1
MainThread 2
True
MainThread 3
Thread-1 2
MainThread 4
True
Thread-1 3
True
Thread-1 4
True

2.面向对象

此方法为新建子类继承threading模块的Thread类,并修改它的run函数

import threading
import time

class test_thread(threading.Thread):
    def __init__(self,name = None):
        threading.Thread.__init__(self,name=name)

    def run(self):
        for i in range(5):
            print(threading.current_thread().name,i)
            time.sleep(2)

thread = test_thread(name = 'TestThread')
thread.start()

for i in range(5):
    print(threading.current_thread().name+' main',i)
    print(thread.name+' is alive',thread.is_alive())
    time.sleep(2)

执行结果

TestThread 0
MainThread main 0
TestThread is alive True
MainThread main 1
TestThread is alive True
TestThread 1
MainThread main 2
TestThread is alive True
TestThread 2
MainThread main 3
TestThread is alive True
TestThread 3
MainThread main 4
TestThread is alive True
TestThread 4
蟹蟹
上一篇 下一篇

猜你喜欢

热点阅读