Python进程与线程学习笔记

一、什么是线程

现有进程,再有线程,

进程提供线程执行程序的前置要求,线程在重组的资源配备下,去执行程序

多线程

二、进程的创建模块---multiprocessing

函数名介绍参数返回值
Process创建一个进程target,args进程对象
函数名介绍参数返回值
start执行进程
join阻塞进程
kill杀死进程
is_alive进程是否存活bool

三、进程池的创建---multiprocessing

函数名介绍参数返回值
Pool进程池创建Processcount进程池对象

函数名介绍参数返回值
apply_async任务加入进程池func,args
close关闭进程池
join等待进程池任务结束

# coding:utf-8

import os
import time
import multiprocessing


def work(count):
    
    # 打印出进程ID os.getpid()
    print(count, os.getpid())
    # 阻塞5秒
    time.sleep(5)

    
    return 'result is %s, pid is %s' % (count, os.getpid())


if __name__ == '__main__':
    #创建进程池,里面有5个进程
    pool = multiprocessing.Pool(5)
    results = []

    for i in range(20):
        result = pool.apply_async(func=work, args=(i, ))
        # results.append(result)

    # for res in results:
    #     print(res.get())
    #
    pool.close()
    pool.join()

三、进程锁

Lock锁,锁一个放一个

 

# coding:utf-8

import os
import time
import multiprocessing


def work(count, lock):
    # 进程池上锁
    lock.acquire()
    # 打印出进程ID os.getpid()
    print(count, os.getpid())
    # 阻塞5秒
    time.sleep(1)
    # 进程池解锁
    lock.release()
    return 'result is %s, pid is %s' % (count, os.getpid())


if __name__ == '__main__':
    #创建进程池,里面有5个进程
    pool = multiprocessing.Pool(5)

    manger = multiprocessing.Manager()
    lock = manger.Lock()
    results = []

    for i in range(20):
        result = pool.apply_async(func=work, args=(i, lock))
        # results.append(result)

    # for res in results:
    #     print(res.get())
    #
    pool.close()
    pool.join()

四、进程间的通信

4.1 队列的创建---multiprocessing

函数名介绍参数返回值
Queue队列的创建mac_cout队列对象

函数名介绍参数返回值
put信息放入队列message
get获取队列信息str

4.2 多进程的总结

 

# coding:utf-8

import time
import json
import multiprocessing

class Work(object):

    def __init__(self, q):
        self.q = q

    def send(self, message):
        if not isinstance(message, str):
            message = json.dumps(message)
        self.q.put(message)

    def send_all(self):
        for i in range(20):
            # 降数据放入队列
            self.q.put(i)
            time.sleep(1)

    def receive(self):
        while 1:
            # 从队列中取数据
            result = self.q.get()
            try:
                res = json.loads(result)
            except:
                res = result
            print('recv is %s' % res)


if __name__ == '__main__':
    
    # 创建队列
    q = multiprocessing.Queue()
    work = Work(q)
    send = multiprocessing.Process(target=work.send, args=({'name': '小慕'},))
    recv = multiprocessing.Process(target=work.receive)
    send_all_p = multiprocessing.Process(target=work.send_all)

    send_all_p.start()
    send.start()
    recv.start()

    send_all_p.join()
    # 终结接收端
    recv.terminate()

五、线程

5.1 线程的创建 --- threading

方法名说明举例
Thread创建线程Thread(target,args)

5.2 线程对象的方法

方法名说明用法
start启动线程start()
join阻塞指导线程执行结束join(timeout=None)
getName获取线程名字getName()
setName设置线程名字setName(name)
is_alive判断线程是否存活is_alive()
setDaemon守护线程setDaemon(True)

5.3 线程的问题

  • 通过线程执行的函数无法获取返回值
  • 多个线程同时修改文件可能造成数据错乱
    # coding:utf-8
    
    import time
    import random
    import threading
    
    lists = ['python', 'django', 'tornado',
             'flask', 'bs5', 'requests', 'uvloop'
    ]
    
    new_lists = []
    
    def work():
        if len(lists) == 0:
            return
        data = random.choice(lists)
        lists.remove(data)
        new_data = '%s_new' % data
        new_lists.append(new_data)
        time.sleep(1)
    
    
    if __name__ == '__main__':
        start = time.time()
        print('old list len:', len(lists))
        t_list = []
        for i in range(len(lists)):
            # 创建多线程
            t = threading.Thread(target=work)
            t_list.append(t)
            t.start()
        
        # 阻塞线程
        for t in t_list:
            t.join()
    
        print('old list:', lists)
        print('new list:', new_lists)
        print('new_list len', len(new_lists))
        print('time is %s' % (time.time() - start))
    

    5.4 线程创建的总结

 

 

六、线程池的创建 

线程池 --- concurrent

方法名说明举例
futures.ThreadPoolExecutor创建线程池tpool=ThreadPoolExecutor(max_workers)

方法名说明用法
submit往线程池中加入任务submit(target,args)
done线程池中的某个线程是否完成了任务done()
result获取当前线程执行任务的结果result()

# coding:utf-8

import time
import os
import threading

from concurrent.futures import ThreadPoolExecutor

# 线程锁
lock = threading.Lock()


def work(i):
    # lock.acquire()
    print(i, os.getpid())
    time.sleep(1)
    # lock.release()
    return 'result %s' % i


if __name__ == '__main__':
    print(os.getpid())
    # 创建线程池
    t = ThreadPoolExecutor(2)
    result = []
    for i in range(20):
        # 往线程池中加入任务
        t_result = t.submit(work, (i, ))
        result.append(t_result)

    for res in result:
        print(res.result())

    

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值