Python 线程和进程

目录

一 、线程

二 、进程


一 、线程

线程是进程的实际工作单位。各线程之间共享分配给进程的资源。当不同的线程需要操作共享数据时,当两个或以上对共享内存的操作发生在并发线程中,并且至少有一个可以改变数据,又没有同步机制的条件下,就会产生竞争条件,可能会导致执行无效代码、bug、或异常行为。

import threading

threading 包用于创建线程。

Python并发之多线程threading(1)_布鲁斯-CSDN博客_python 多线程并发Threading用于提供线程相关的操作。线程是应用程序中工作的最小单元,它被包含在进程之中,是进程中的实际运作单位。当不同的线程需要操作共享数据时,当两个或以上对共享内存的操作发生在并发线程中,并且至少有一个可以改变数据,又没有同步机制的条件下,就会产生竞争条件,可能会导致执行无效代码、bug、或异常行为。需要通过某些机制控制共享数据的读写,确保同一个时刻只能有一个线程能写数据。Thre...https://blog.csdn.net/biheyu828/article/details/83019392

import threading
import time


def music(data):
    print("bengin listen music: {}".format(time.ctime()))
    time.sleep(2)
    print(str(data))
    print("music end: {}".format(time.ctime()))


def movie(data):
    print("bengin look movie: {}".format(time.ctime()))
    time.sleep(5)
    print(str(data))
    print("movie end: {}".format(time.ctime()))


thread_list = []

th1 = threading.Thread(target=music, args=("love.mp3",))
th2 = threading.Thread(target=movie, args=("Anit.avi",))
thread_list.append(th1)
thread_list.append(th2)

for th in thread_list:
    th.start()

for th in thread_list:
    th.join()

print("main thread continue: {}".format(time.ctime()))

二 、进程

 1. 如果使用多进程就可以真正利用多核,因为各进程之间是相互独立的,不共享资源,可以在不同的核上执行不同的进程,达到并行的效果。

2. 多核CPU可以同时执行多个进程,建议有几个核创建几个进程。 
多核CPU 是否能同时执行多个进程? - 知乎如果能,可以同时最多执行几个进程?https://www.zhihu.com/question/271821176

 查看电脑CPU核数的方法https://jingyan.baidu.com/article/4f34706e1c6757e386b56d57.htmlicon-default.png?t=M1L8https://jingyan.baidu.com/article/4f34706e1c6757e386b56d57.html

multiprocessing 包用于创建进程,引入进程池概念。

from multiprocessing import Pool

Pool类下的几种方法:

【Python】Python多进程库multiprocessing中进程池Pool的返回值顺序_小白兔de窝-CSDN博客_python 进程池 顺序问题起因最近要将一个文本分割成好几个topic,每个topic设计一个regressor,各regressor是相互独立的,最后汇总所有topic的regressor得到总得预测结果。没错!类似bagging ensemble!只是我没有抽样。文本不大,大概3000行,topic个数为8,于是我写了一个串行的程序,一个topic算完之后再算另一个topic。可是我在每个topic中用了GridSe...https://blog.csdn.net/ztf312/article/details/80337255

https://jingyan.baidu.com/article/4f34706e1c6757e386b56d57.htmlicon-default.png?t=M1L8https://jingyan.baidu.com/article/4f34706e1c6757e386b56d57.html

# -*- coding:utf-8 -*-
from multiprocessing import Pool as Pool
import time
import random


def func(msg):
    print('msg:', msg)
    sleep_num = random.randint(1, 20)
    time.sleep(sleep_num)
    print('end:')
    return msg


if __name__ == '__main__':
    # 多进程要在main 中执行,不然会报错
    pool = Pool(processes=3)  # 我们也可自己设置,但是要考虑自己计算机的性能
    # pool = Pool()           # 这个参数可以不设置,如果不设置函数会跟根据计算机的实际情况来决定要运行多少个进程

    result = []
    for i in range(1, 100):
        msg = 'hello %d' % (i)
        # 非阻塞,添加任务后立即执行,不会等待进程结束
        res = pool.apply_async(func, (msg,))  # 只有apply_async可以有返回值,apply,map,imap不可以设置返回值
        # 阻塞式只有apply_async可以有返回值,apply,map,imap不可以设置返回值
        # res = pool.apply(func, (msg,))      # 此方式没有返回值
        result.append(res)

    print('Mark~~~~~~~~~~~~~~~')
    pool.close()  # 添加任务结束
    pool.join()   # 堵住主进程,调用join之前,先调用close函数,否则会出错。执行完close后不会有新的进程加入到pool,join函数等待所有子进程结束
    for res in result:
        print("sub_process return: ", res.get())
    print('sub-process done')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值