一 线程的启动与停止
线程需要使用线程库threading。
from threading import Thread
import time
################直接调用的方式创建线程################
# 定义多线程要运行函数
def countdown(num):
while num > 0:
print("T-Minus",num)
num -= 1
time.sleep(1)
t = Thread(target=countdown,args=(10,))
t.start()
##################继承的方式创建线程##################
class MyThread(Thread):
def __init__(self,num):
#Thread.__init__(self)
super(MyThread,self).__init__()
self.num = num
def run(self):
while self.num > 0:
print("self.num=>", self.num)
self.num -= 1
time.sleep(1)
t = MyThread(10)
t.run()
二 守护线程 和 前台线程
什么是守护线程?
就是在后台默默执行的线程,比如Java的GC就是一守护线程
当主线程结束的时候,无论守护线程是否运行完毕,是否成功,守护线程子线程都会立即结束
什么是非守护线程?
当主线程结束的时候,必须等待其他这些非守护线程运行结束才能结束
非守护线程的例子:
from threading import Thread
import time
def show(name):
for i inrange(5):
time.sleep(0.5)
print("%s --> %s" %(name,i))
if __name__ == '__main__':
t =Thread(target=show,args=("守护线程",))
#非守护线程:主线程必须等非守护线程全部结束才能结束
t.start()
time.sleep(2)
print("main thread ending")
结果:
守护线程 --> 0
守护线程 --> 1
守护线程 --> 2
main thread ending
守护线程 --> 3
守护线程 --> 4
from threading import Thread
import time
def show(name):
for i inrange(5):
time.sleep(0.5)
print("%s --> %s" %(name,i))
if __name__ == '__main__':
t =Thread(target=show,args=("守护线程",))
#守护线程:主线程结束,守护线程也必须结束掉
t.setDaemon(True)
t.start()
time.sleep(2)
print("main thread ending")
结果:
守护线程 --> 0
守护线程 --> 1
守护线程 --> 2
main thread ending
三 多线程的JOIN
我们知道在java中,Thread有一静态方法,join,表示一个线程B加入线程A的尾部,在A执行完毕之前,B不能执行;而且还带有timeout参数,表示超过某个时间则停止等待,变为可运行状态,等待CPU的调度
3.1 非守护线程
Python中,默认情况下,如果不加join语句,那么主线程不会等到当前线程结束才结束,但却不会立即杀死该线程
from threading import Thread
import time
class ShowThread(Thread):
def __init__(self,name):
super(ShowThread,self).__init__()
self.name = name
def run(self):
for i inrange(5):
time.sleep(0.5)
print("[%s] --> %s" % (self.name, i))
def present():
for i inrange(5):
print("[present] --> %s" %(i))
if __name__ == '__main__':
A =ShowThread("show")
A.start()
present()
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
[show] --> 0
[show] --> 1
[show] --> 2
[show] --> 3
[show] --> 4
如果加上join,则会阻塞当前线程,其他线程包括主线程,都必须等待该线程运行完毕,才能继续运行
if __name__ == '__main__':
A =ShowThread("show")
A.start()
A.join()
present()
结果:
[show] --> 0
[show] --> 1
[show] --> 2
[show] --> 3
[show] --> 4
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
我们也可以指定阻塞多长时间,如果超过这个时间,那么其他线程不再继续等待,可以被CPU调度了
if __name__ == '__main__':
A =ShowThread("show")
A.start()
A.join(2)
present()
结果:
[show] --> 0
[show] --> 1
[show] --> 2
[show] --> 3
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
[show] --> 4
3.2 守护线程
对于守护线程,如果我们没有使用join,那么主线程运行完毕之后,守护线程无论是否运行完毕,都结束了
if __name__ == '__main__':
A =ShowThread("show")
A.setDaemon(True)
A.start()
time.sleep(0.5)
present()
结果:
[show] --> 0
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
对于守护线程,如果使用join,那么守护线程就会阻塞主线程,主线程需要等待守护线程运行结束才能运行
if __name__ == '__main__':
A =ShowThread("show")
A.setDaemon(True)
A.start()
time.sleep(0.5)
A.join()
present()
结果:
[show] --> 0
[show] --> 1
[show] --> 2
[show] --> 3
[show] --> 4
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
我们对join指定阻塞时间,如果超过这个时间,那么守护线程就不再阻塞主线程,主线程就可以继续运行,运行结束,无论守护线程是否运行完毕,都给结束掉
if __name__ == '__main__':
A =ShowThread("show")
A.setDaemon(True)
A.start()
A.join(timeout=1)
present()
结果:
[show] --> 0
[show] --> 1
[present] --> 0
[present] --> 1
[present] --> 2
[present] --> 3
[present] --> 4
四 线程锁
一个进程下可以启动多个线程,多个线程共享父进程的内存空间,也就意味着每个线程可以访问同一份数据,此时,如果2个线程同时要修改同一份数据,会出现什么状况?
当一个线程调用锁的acquire()方法获得锁时,锁就进入“locked”状态。每次只有一个线程可以获得锁。如果此时另一个线程试图获得这个锁,该线程就会变为“blocked”状态,称为“同步阻塞”(参见多线程的基本概念)。
直到拥有锁的线程调用锁的release()方法释放锁之后,锁进入“unlocked”状态。线程调度程序从处于同步阻塞状态的线程中选择一个来获得锁,并使得该线程进入运行(running)状态。
from threading import Thread
from threading import Lock
import time
class Ticket(object):
def __init__(self,tickets):
self.tickets = tickets
def sell(self):
self.tickets -= 1
class TicketSeller(Thread):
def __init__(self,ticket):
super(TicketSeller,self).__init__()
self.ticket = ticket
self.lock = Lock()
def run(self):
for i inrange(5):
time.sleep(1)
self.lock.acquire()
self.ticket.sell()
self.lock.release()
print("%s ===%s" %(self.getName(),ticket.tickets))
if __name__ == '__main__':
ticket = Ticket(500)
sellerList = []
for i in range(5):
seller = TicketSeller(ticket)
seller.start()
sellerList.append(seller)
for seller in sellerList:
seller.join()
print("剩余票数:%s" %(ticket.tickets))
五 递归锁与信号量
5.1 什么是信号量
我们先看一下Java中的实现,Semaphore=>
Semaphore是用来保护一个或者多个共享资源的访问,Semaphore内部维护了一个计数器,其值为可以访问的共享资源的个数。一个线程要访问共享资源,先获得信号量,如果信号量的计数器值大于1,意味着有共享资源可以访问,则使其计数器值减去1,再访问共享资源。
如果计数器值为0,线程进入休眠。当某个线程使用完共享资源后,释放信号量,并将信号量内部的计数器加1,之前进入休眠的线程将被唤醒并再次试图获得信号量。
就好比一个厕所管理员,站在门口,只有厕所有空位,就开门允许与空侧数量等量的人进入厕所。多个人进入厕所后,相当于N个人来分配使用N个空位。为避免多个人来同时竞争同一个侧卫,在内部仍然使用锁来控制资源的同步访问
import java.util.Collection;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.ReentrantLock;
public class ResourceManager {
/** 可重入锁,对资源列表进行同步 */
private final ReentrantLock lock = new ReentrantLock();
/** 可使用的资源列表 */
private final LinkedList<Object> resourceList = new LinkedList<Object>();
/** 信号量 */
private Semaphore semaphore ;
publicResourceManager(Collection<Object> resourceList) {
this.resourceList.addAll(resourceList);
this.semaphore = new Semaphore(resourceList.size(), true);
}
/**获取资源*/
public Object acquire() throws InterruptedException {
semaphore.acquire();
Object resource = null;
lock.lock();
try {
resource = resourceList.poll();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
return resource;
}
/**释放或则归还资源*/
public void release(Object resource){
lock.lock();
try {
resourceList.addLast(resource);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
semaphore.release();
}
}
public class Consumer implements Runnable{
private ResourceManager rm;
publicConsumer() {
}
publicConsumer(ResourceManager rm) {
this.rm = rm;
}
@Override
public void run() {
Object resource = null;
try {
resource = rm.acquire();
System.out.println(Thread.currentThread().getName()+" work on " + resource);
/*用resource做工作*/
Thread.sleep(5000);
System.out.println(Thread.currentThread().getName() + " finish on " + resource);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
/*归还资源*/
if (resource != null) {
rm.release(resource);
}
}
}
public ResourceManager getRm() {
return rm;
}
public void setRm(ResourceManager rm) {
this.rm = rm;
}
}
public class SignalClient {
public staticvoid main(String[] args) {
/*准备2个可用资源*/
List<Object> resourceList = new ArrayList<Object>();
resourceList.add("Resource1");
resourceList.add("Resource2");
/*准备工作任务*/
final ResourceManager rm = new ResourceManager(resourceList);
Consumer consumer = new Consumer(rm);
/*启动10个任务*/
ExecutorServiceservice = Executors.newCachedThreadPool();
for (int i = 0; i < 10; i++) {
service.submit(consumer);
}
service.shutdown();
}
}
python中的实现
from threading import Thread
from threading import Lock
from threading import Semaphore
from queue import Queue
import time
'''负责资源的存放,以及维护Semaphore的状态'''
class ResouceManager(object):
def __init__(self,resourceList):
self.resourceList = resourceList
self.lock = Lock()
self.sem = Semaphore(value=len(resourceList))
'''获取资源'''
def acquire(self):
self.sem.acquire()#内部计数器减1
self.lock.acquire()
resource = self.resourceList.pop()
self.lock.release()
return resource
'''释放资源'''
def release(self,resource):
self.lock.acquire()
self.resourceList.append(resource)
self.lock.release()
self.sem.release()#内部计数器加1
class Consumer(Thread):
def __init__(self,rm):
super(Consumer, self).__init__()
self.rm = rm
def run(self):
resource = self.rm.acquire()
print("%s work onthe resource: %s" %(self.getName(),resource))
time.sleep(3)
self.rm.release(resource)
if __name__ == "__main__":
'''构建资源'''
resourceList = ["resource1","resource2"]
rm =ResouceManager(resourceList)
for i in range(10):
consumer = Consumer(rm)
consumer.start()
5.2RLock递归锁或者叫做可重入锁
它与Lock的区别在于,RLock允许在一个线程被多次acquire,但是Lock却不允许这种情况,acquire和release必须成对出现。
from threading import RLock
import time
lock = RLock()
def run1():
print("grab the first part data")
lock.acquire()
global num
num += 1
lock.release()
return num
def run2():
print("grab the second part data")
lock.acquire()
global num2
num2 += 1
lock.release()
return num2
def run3():
lock.acquire()
res = run1()
print('--------between run1 and run2-----')
res2 = run2()
lock.release()
print(res, res2)
六Condition
from threading import Thread,Condition
import time
'''
所谓条件变量,即这种机制是在满足了特定的条件后,线程才可以访问相关的数据
'''
class Goods(object):
def __init__(self):
self.count = 0
def add(self, num=1):
self.count += num
def sub(self):
if self.count>=0:
self.count -= 1
def isEmpty(self):
return self.count <= 0
class Producer(Thread):
def __init__(self, condition, goods, sleeptime = 1):
super(Producer,self).__init__()
self.condition = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
condition = self.condition
goods = self.goods
while True:
condition.acquire() # 锁住资源
goods.add()
print("产品数量:", goods.count, "生产者线程")
condition.notifyAll() # 唤醒所有等待的线程--》其实就是唤醒消费者进程
condition.release() # 解锁资源
time.sleep(self.sleeptime)
class Consumer(Thread):#消费者类
def __init__(self,condition,goods,sleeptime = 2):#sleeptime=2
super(Consumer, self).__init__()
self.condition = condition
self.goods = goods
self.sleeptime = sleeptime
def run(self):
condition = self.condition
goods = self.goods
while True:
time.sleep(self.sleeptime)
condition.acquire()#锁住资源
while goods.isEmpty():#如无产品则让线程等待
condition.wait()
goods.sub()
print("产品数量:",goods.count,"消费者线程")
condition.release()#解锁资源
if __name__ == "__main__":
g =Goods()
c = Condition()
pro = Producer(c, g)
pro.start()
con = Consumer(c, g)
con.start()
七 同步队列
from threading import Thread,Condition
import time
from queue import Queue
class Worker(Thread):
def __init__(self,index,queue):
super(Worker, self).__init__()
self.index = index
self.queue = queue
def run(self):
while True:
time.sleep(1)
item = self.queue.get()
if item is None:
break
print("序号:", self.index, "任务", item, "完成")
# task_done方法使得未完成的任务数量-1
self.queue.task_done()
if __name__ == "__main__":
'''
初始化函数接受一个数字来作为该队列的容量,如果传递的是
一个小于等于0的数,那么默认会认为该队列的容量是无限的.
'''
queue = Queue(0)
for i inrange(10):
queue.put(i) # put方法使得未完成的任务数量+1
for i in range(2):
Worker(i, queue).start() # 两个线程同时完成任务
八 多进程
多任务可以由多进程完成,也可以由一个进程内的多线程完成。
Multiprocessing模块用于跨平台多进程模块,提供一个Process类代表一个进程对象
创建子进程时,只需要传入一个执行函数和函数的参数,创建一个Process实例,用start()方法启动,这样创建进程比fork()还要简单。
join()方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步。
from multiprocessing import Process
import time
def f(name):
time.sleep(2)
print('hello', name)
if __name__ == '__main__':
p = Process(target=f, args=('bob',))
p.start()
p.join()
from multiprocessing import Process
import time
def info(title):
print(title)
print('module name:', __name__)
print('parent process:', os.getppid())
print('process id:', os.getpid())
print("\n\n")
def f(name):
info('\033[31;1mfunction f\033[0m')
print('hello', name)
if __name__ == '__main__':
info('\033[32;1mmain process line\033[0m')
p = Process(target=f, args=('bob',))
p.start()
p.join()
九 进程间通讯
Process之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。
我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:
from multiprocessing import Process, Queue
import os, time, random
# 写数据进程执行的代码:
def write(q):
print("process to write: %s" %os.getpid())
for value in range(5):
print("Put [%s] to queue: " %value)
q.put(value)
time.sleep(random.random())
def read(q):
print("process to read: %s" % os.getpid())
while True:
value = q.get(True)
print('Get [%s] from queue.' % value)
if __name__ == "__main__":
# 父进程创建Queue,并传给各个子进程:
q = Queue()
pw = Process(target=write,args=(q,))
pr = Process(target=read, args=(q,))
# 启动子进程pw,写入:
pw.start()
# 等待pw结束:
pw.join()
# 启动子进程pr,读取:
pr.start()
# pr进程里是死循环,无法等待其结束,只能强行终止:
#pr.terminate()
九 进程池
如果要启动大量的子进程,可以用进程池的方式批量创建子进程:
对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。
请注意输出的结果,task 0,1,2,3是立刻执行的,而task 4要等待前面某个task完成后才执行,这是因为Pool的默认大小在我的电脑上是4,因此,最多同时执行4个进程。这是Pool有意设计的限制,并不是操作系统的限制。如果改成:
p = Pool(5)
就可以同时跑5个进程。
由于Pool的默认大小是CPU的核数,如果你不幸拥有8核CPU,你要提交至少9个子进程才能看到上面的等待效果。
from multiprocessing import Pool
import os, time, random
def long_time_task(name):
print('Run task %s (%s)...' % (name, os.getpid()))
start = time.time()
time.sleep(random.random() * 3)
end = time.time()
print('Task %s runs %0.2f seconds.' % (name, (end - start)))
if __name__=='__main__':
print('Parent process %s.' % os.getpid())
p = Pool(4)
for i in range(5):
p.apply_async(long_time_task, args=(i,))
print('Waiting for all subprocesses done...')
p.close()
p.join()
print('All subprocesses done.')
十 子进程
很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。
subprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。
如果子进程还需要输入,则可以通过communicate()方法输入:
下面的例子演示了如何在Python代码中运行命令nslookup www.python.org,这和命令行直接运行的效果是一样的:
import subprocess
print('$ nslookup www.python.org')
r = subprocess.call(['nslookup', 'www.python.org'])
print('Exit code:', r)
print('$ nslookup')
p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output, err = p.communicate(b'set q=mx\npython.org\nexit\n')
print(output.decode('utf-8'))
print('Exit code:', p.returncode)