Python多线程

  进程是程序的实体,线程是操作系统能够进行运算调度的最小单位。线程被包含在进程中,是进程中实际处理单位。一条线程就是一堆的指令集合。我们可以使用多线程来让一个程序加速运行,让多个线程同时处理进程的不同部分。


一、threading的Thread类

先看几个 threading.Thread 类方法

class Thread:
	""""""A class that represents a thread of control."""
	
	def __init__(self, group=None, target=None, name=None,
                 args=(), kwargs=None, *, daemon=None):
    	"""
    	*target* is the callable object to be invoked by the run() method.
        *args* is the argument tuple for the target invocation.
        *name* is the thread name. By default, a unique name is constructed of
        the form "Thread-N" where N is a small decimal number.
        """

	def start(self):
		"""Start the thread's activity."""
		
	def run(self):
		"""Method representing the thread's activity."""
		
	def join(self, timeout=None):
		"""Wait until the thread terminates."""
方法描述
getName(self)返回线程的名字
isAlive(self)若线程正在运行,则返回True
isDaemon(self)返回线程的Deamon标志
join(self, timeout=None)程序运行,直到线程结束,最多阻塞timeout秒
run(self)定义线程的功能函数
setDeamon(self, deamonic)把线程的deamon标志设为deamonic
setName(self, name)设置线程的名字
start(self)线程开始执行


二、创建线程

创建两个线程,分别执行函数funct1和funct2的功能,函数参数为arg1, arg2, …

import threading
t1 = threading.Thread(target=funct1, args=(arg1, arg2,))
t2 = threading.Thread(target=funct2, args=(arg1, arg2,))

举个例子:一个人吃饭和写作业,分别需要5s和3s,使用多线程执行任务:

import threading
from time import sleep, ctime

def eat():
	print("Begin eatting at \t %s" %ctime())
	sleep(5)
	print("End eatting at \t %s" %ctime())

def study():
	print("Begin studying at \t %s" %ctime())
	sleep(3)
	print("End studing \t %s" %ctime())

threads = []
t1 = threading.Thread(target=eat)
threads.append(t1)
t2 = threading.Thread(target=study)
threads.append(t2)

if __name__ == "__main__":
	for t in threads:
		t.start()

程序执行结果如下:边吃饭边赶作业,吃饭需要5s,写作业需要3s,总耗时为5s

Begin eatting at 	 Sat Oct  5 14:30:21 2019
Begin studying at 	 Sat Oct  5 14:30:21 2019
End studing 		 Sat Oct  5 14:30:24 2019
End eatting at 		 Sat Oct  5 14:30:26 2019

***Repl Closed***

下面是使用单线程的结果:

import threading
from time import sleep, ctime

def eat():
	print("Begin eatting at \t %s" %ctime())
	sleep(5)
	print("End eatting at \t\t %s" %ctime())

def study():
	print("Begin studying at \t %s" %ctime())
	sleep(3)
	print("End studing \t\t %s" %ctime())

if __name__ == "__main__":
	eat()
	study()

输出结果如下:

Begin eatting at 	 Sat Oct  5 14:33:42 2019
End eatting at 		 Sat Oct  5 14:33:47 2019
Begin studying at 	 Sat Oct  5 14:33:47 2019
End studing 		 Sat Oct  5 14:33:50 2019

***Repl Closed***


三、join()函数与setDaemon()函数

join()函数:在子线程执行完成之前,这个子线程的父线程将一直被阻塞。就是说,当调用join()的子进程没有结束之前,主进程不会往下执行。对其它子进程没有影响。

if __name__ == "__main__":
	for t in threads:
		t.start()
		t.join()

得到的结果是每一条任务都顺序执行(因为对每一个线程都设置了Deamon为True)

Begin eatting at 	 Sat Oct  5 14:51:33 2019
End eatting at 	 Sat Oct  5 14:51:38 2019
Begin studying at 	 Sat Oct  5 14:51:38 2019
End studing 	 Sat Oct  5 14:51:41 2019

***Repl Closed***

setDeamon()有时候我们需要的是 只要主线程完成了,不管子线程是否完成,都要和主线程一起退出,这时就可以用setDaemon方法。

if __name__ == "__main__":
	for t in threads:
		t.setDaemon(True)
		t.start()
	print("All over %s" %ctime)

结果如下:当个主线程执行完后,不论子线程是否还在执行,直接结束程序:

Begin eatting at 	 Sat Oct  5 14:54:45 2019
Begin studying at 	 Sat Oct  5 14:54:45 2019
All over <built-in function ctime>

***Repl Closed***


四、其他函数的使用

1、getName(self):获取线程的名字

threads = []
t1 = threading.Thread(target=eat)
t1.setName("eat")
threads.append(t1)
t2 = threading.Thread(target=study)
t2.setName("study")
threads.append(t2)

if __name__ == "__main__":
	for t in threads:
		print(t.getName())

输出结果:

eat
study

***Repl Closed***

2、同步锁
多个线程同时操作同一个共享资源,所以导致冲突,这种情况就需要用同步锁来解决。

def add():
	lock.acquire()  	#加同步锁
	a += 1				# 修改变量
	lock.release() 	#解锁

关于多线程的运用,下次再说吧 完结~
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值