Python多线程学习笔记 1
参考:
https://www.cnblogs.com/lyroge/p/6029326.html
https://www.runoob.com/python3/python3-multithreading.html
https://blog.csdn.net/weixin_40481076/article/details/101594705
threading模块
threading模块提供以下方法
threading.currentThread(): //返回当前的线程变量
threading.enumerate(): //返回一个包含正在运行的线程的列表
//返回正在运行的线程数量,与len(threading.enumerate())有同样效果
threading.activeCount():
threading.Lock(): //互斥锁
threading.RLock(): //递归锁
除了使用方法之外,threading模块还提供了Thread类来处理线程。Thread类提供了以下方法
import threading
t = threading.Thread(target = func, args = (*parameter,))
run(): //表示线程活动的方法
t.start(): //启动线程活动
//在子线程完成运行之前,这个子线程的父线程将一直被阻塞。这阻塞调用线程直至线程的join() 方法被调用中止-正常退出或者是可选的超时发生。
//父线程是什么?线程的join()方法如何被调用中止?
t.join([time])
active = t.isAlive(): //返回活动是否活动
thread_name = getName(): //返回线程名
t.setName("Thread_name"): //设置线程名
t.setDaemon(True): //设置daemon属性
线程的daemon属性
除了threading模块之外,python3还有_thread模块可以创建线程。
二者创建的线程都拥有daemon属性,官方文档的解释是:
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.
The entire Python program exits when no alive non-daemon threads are left.
意思是说:这个属性为一个布尔值,表示是否为一个守护进程,且这个属性设置必须在线程的start方法开始之前调用。它的值继承自主线程,主线程的daemon属性为False且所有从主线程创建的线程都是daemon = False的。
下面一句说明了,python主程序只有在所有非守护线程都结束的时候才会退出,而无视守护线程是否正在运行。
import time
import _thread
import threading
def print_time(thread_name, delay):
count = 0
while count < 5:
t = threading.currentThread()
time.sleep(delay)
count += 1
print ("%s: %s daemon:%s" % ( thread_name, time.ctime(time.time()), t.daemon ))
t1 = _thread.start_new_thread(print_time, (("Thread-1", 2, )))
t2 = threading.Thread(target = print_time, args = ("Thread-2", 4, ))
t2.start()
通过以上代码,验证得到_thread模块创建的线程daemon属性默认为True,threading模块创建线程的daemon属性默认为False。
创建线程
'''
普通创建方式
'''
# def run(n):
# print('task',n)
# time.sleep(1)
# print('2s')
# time.sleep(1)
# print('1s')
# time.sleep(1)
# print('0s')
# time.sleep(1)
#
# if __name__ == '__main__':
# t1 = threading.Thread(target=run,args=('t1',)) # target是要执行的函数名(不是函数),args是函数对应的参数,以元组的形式存在
# t2 = threading.Thread(target=run,args=('t2',))
# t1.start()
# t2.start()
'''
自定义线程:继承threading.Thread来定义线程类,其本质是重构Thread类中的run方法
'''
# class MyThread(threading.Thread):
# def __init__(self,n):
# super(MyThread,self).__init__() #重构run函数必须写
# self.n = n
#
# def run(self):
# print('task',self.n)
# time.sleep(1)
# print('2s')
# time.sleep(1)
# print('1s')
# time.sleep(1)
# print('0s')
# time.sleep(1)
#
# if __name__ == '__main__':
# t1 = MyThread('t1')
# t2 = MyThread('t2')
# t1.start()
# t2.start()