python 进程 线程

进程引包multiprocessing,进程是资源最小单位,每个进程拥有自己的资源,不涉及资源互斥

线程引包threading,线程是是cpu调度的最小单位,可以访问共享资源,使用互斥锁对共享资源加锁

复制代码
import threading
import multiprocessing
import time

count = 0
mutex = threading.Lock()

def test():
    global count
    mutex.acquire()
    for i in range(100):
        count += 1
        time.sleep(0.02)
    mutex.release()
    print(f"thread is {threading.current_thread()}count is {count}")

def test1():
    global count
    mutex.acquire()
    for i in range(100):
        count += 1
        time.sleep(0.02)
    mutex.release()
    print(f"thread is {threading.current_thread()}count is {count}")


if __name__ == '__main__':
    threading.Thread(target=test).start()
    threading.Thread(target=test1).start()
    # multiprocessing.Process(target=test).start()
    # multiprocessing.Process(target=test).start()

加锁前:原因对count竞争性操作

thread is <Thread(Thread-1, started 5872)>count is 200

thread is <Thread(Thread-2, started 8124)>count is 200

加锁后输出:

thread is <_MainThread(MainThread, started 5960)>count is 100

thread is <_MainThread(MainThread, started 10076)>count is 100

相关推荐
用户7610304473716 分钟前
【转战智能眼镜开发】ROKID AIUI 小游戏 亚马逊标枪项目实战讲解
前端
风卿17 分钟前
看着AI写代码太孤独了,来欣赏星云吧:一个DSH 装饰插件
前端·javascript
2601_9679873722 分钟前
python判断变量名不要调用任何函数实现
python·函数·语法·判断·变量名
牧艺26 分钟前
弹层不用再手算坐标了:CSS Anchor Positioning 从原理到可上线
前端·javascript·css
用户老李37 分钟前
YOLO 目标检测自学教程 07:YOLOv3——多尺度预测
前端
moshuying1 小时前
ESP32 墨水屏金价牌(上):从点亮到把图片推过去
前端
卷无止境1 小时前
SALib敏感性分析的python库学习笔记
后端·python
李剑一1 小时前
别再抬杠,前端岗已经没了!无论前后端,我们最终都要成“全干”工程师
前端·面试
Highcharts.js1 小时前
Highcharts 仪表盘与速度仪图表库介绍
前端·信息可视化·仪表板·highcharts·图表开发·图表库·仪表可视化
SL_staff2 小时前
私有化低代码:面向强监管行业的可控数字化实践
java·低代码