并发编程之多线程操作

一 threading 模块介绍

multiprocess模块的完全模仿了threading模块的接口,二者在使用层面,有很大的相似性

二 开启线程的两种方式

"""
方式一:直接调用threading模块下 Thread 类方法
"""
from threading import Thread
import time

def sayhi(name):
    time.sleep(2)
    print('%s say hello' %name)

if __name__ == '__main__':
    t=Thread(target=sayhi,args=('egon',))
    t.start()
    print('主线程')

"""
方式二:继承Thread类,重写run()方法
"""
from threading import Thread
import time

class Sayhi(Thread):
    def __init__(self,name):
        super().__init__()
        self.name=name
        
    def run(self):
        time.sleep(2)
        print('%s say hello' % self.name)

if __name__ == '__main__':
    t = Sayhi('egon')
    t.start()
    print('主线程')

三 在一个进程下开启多线程和在一个进程下开启多个子进程的区别

谁开启的速度快

"""
在主进程下开启线程
"""
from threading import Thread

def work():
    print('hello')

if __name__ == '__main__':
    t=Thread(target=work)
    t.start()
    print('主线程/主进程')
# 执行结果如下,几乎是t.start ()的同时就将线程开启了,然后先打印出了hello,证明线程的创建开销极小
hello
主线程/主进程


"""
在主进程下开启子进程
"""
from multiprocessing import Process

def work():
    print('hello')

if __name__ == '__main__':
    #在主进程下开启子进程
    p=Process(target=work)
    p.start()
    print('主线程/主进程')
    
# 执行结果如下,p.start ()将开启进程的信号发给操作系统后,操作系统要申请内存空间,让好拷贝父进程地址空间到子进程,开销远大于线程
主线程/主进程
hello

查看PID

"""
在主进程下开启多个线程,每个线程的PID都跟主进程的PID一样
"""
from threading import Thread
import os

def work():
    print('hello',os.getpid())

if __name__ == '__main__':
    t1=Thread(target=work)
    t2=Thread(target=work)
    t1.start()
    t2.start()
    print('主线程/主进程pid',os.getpid())

# 执行结果:
hello 5760
hello 5760
主线程/主进程pid 5760



"""
开启多个进程,每个进程都有不同的PID
"""
from multiprocessing import Process
import os

def work():
    print('hello',os.getpid())

if __name__ == '__main__':
    p1=Process(target=work)
    p2=Process(target=work)
    p1.start()
    p2.start()
    print('主线程/主进程',os.getpid())

# 执行结果
主线程/主进程 7951
hello 7952
hello 7953

同一进程内的线程共享该进程的数据

"""
进程之间的地址空间是隔离的
"""
from multiprocessing import Process
import os

def work():
    global n
    n=0

if __name__ == '__main__':
    n=100
    p=Process(target=work)
    p.start()
    p.join()
    print('主',n)

# 执行结果如下,子进程p已经将自己的全局的n改成了0,但改的仅仅是它自己的,查看父进程的n仍然为100100


"""
在同一个进程内开启的多个线程是共享该进程的地址空间的
"""
from threading import Thread
import os

def work():
    global n
    n=0

if __name__ == '__main__':
    n=100
    t=Thread(target=work)
    t.start()
    t.join()
    print('主',n)

# 执行结果如下, 查看结果为0,因为同一进程内的线程之间共享进程内的数据0

四 Thread 对象的其他属性和方法

Thread 实例对象的方法:

1 isAlive():返回线程是否活动的
2 getName():返回线程名
3 setName():设置线程名

threading 模块提供的一些方法:

threading.currentThread():返回当前的线程变量
threading.enumerate():返回一个包含正在运行的线程的list,正在运行指线程启动后、结束前,不包括启动前和终止后的线程
threading。activeCount():返回正在运行的线程数量

实例

from threading import Thread
import threading
from multiprocessing import Process
import os

def work():
    import time
    time.sleep(3)
    print(threading.current_thread().getName())

if __name__ == '__main__':
    #在主进程下开启线程
    t=Thread(target=work)
    t.start()

    print(threading.current_thread().getName())
    print(threading.current_thread()) #主线程
    print(threading.enumerate()) #连同主线程在内有两个运行的线程
    print(threading.active_count())
    print('主线程/主进程')
"""
执行结果:
MainThread
<_MainThread(MainThread, started 140735268892672)>
[<_MainThread(MainThread, started 140735268892672)>, <Thread(Thread-1, started 123145307557888)>]
主线程/主进程
Thread-1
"""

五 守护线程

无论是进程还是线程,都遵循:守护xxx会等待主xxx运行完毕后被销毁

需要强调的是:运行完毕并非终止运行

1 对主进程来说,主进程在其他代码结束后就已经算运行完毕了(守护进程在此时就被回收),然后主进程会一直等非守护的子进程都运行完毕后回收子进程的资源(否则会产生僵尸进程),才会结束
2 对主线程来说,主线程在其他非守护线程运行完毕后才算运行完毕(守护线程在此时就被回收),因为主线程的结束意味着进程的结束,进程整体的资源都将被回收,而进程必须保证非守护线程都运行完毕后才能结束
from threading import Thread
import time
def sayhi(name):
    time.sleep(2)
    print('%s say hello' %name)

if __name__ == '__main__':
    t=Thread(target=sayhi,args=('egon',))
    t.setDaemon(True) #必须在t.start()之前设置
    t.start()

    print('主线程')
    print(t.is_alive())
"""
执行结果:
主线程
True
"""

六 信号量Semaphore

  信号量也是一把锁,可以指定信号量为5,对比互斥锁同一时间只能有一个任务抢到锁去执行,信号量同一时间可以有5个任务拿到锁去执行,如果说互斥锁是合租房屋的人去抢一个厕所,那么信号量就相当于一群路人争抢公共厕所,公共厕所有多个坑位,这意味着同一时间可以有多个人上公共厕所,但公共厕所容纳的人数是一定的,这便是信号量的大小

from threading import Thread,Semaphore
import threading
import time

def func():
    sm.acquire()
    print('%s get sm' %threading.current_thread().getName())
    time.sleep(3)
    sm.release()

if __name__ == '__main__':
    sm=Semaphore(5)
    for i in range(23):
        t=Thread(target=func)
        t.start()

"""
解析:
Semaphore 管理一个内置的计数器
每当调用 acquire() 时内置计数器 -1
调用 release() 时内置计数器 +1
计数器不能小于0,当计数器为0时,acquire() 将阻塞线程直到其他线程调用 release()
"""

猜你喜欢

转载自www.cnblogs.com/xuzewen/p/9113391.html