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

相关推荐
杜子不疼.38 分钟前
从 Apache HTTP Server 到 CivetWeb:在鸿蒙 PC 的 3.1 MiB HAP 里嵌入 Web 服务器
前端·apache·harmonyos
kyriewen1 小时前
AI 生成率进了 KPI,最慌的是写代码最快的人
前端·javascript·程序员
SoaringHeart2 小时前
Flutter组件封装:聊天气包图片组件NChatBubble
前端·flutter
狗头大军之江苏分军2 小时前
三个月的电商心得
前端·后端
持敬chijing3 小时前
JAVA与CVE漏洞4-Log4J 漏洞原理与实现
java·网络安全·log4j·系统安全·网络攻击模型·安全威胁分析
软件技术NINI3 小时前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
东莞市云毅网络有限公司4 小时前
用 Node 做收录快照的周对比:差集、阈值与告警
python·sqlite·自动化运维·geo·数据监测
会编程的吕洞宾4 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring
山楂树の5 小时前
Python Pandas 数据处理:数据读取、筛选、清洗、排序与分组
开发语言·python·pandas
Rain的Java大神之路5 小时前
Spring Boot 4 + Spring AI 2.0 迁移实战:别急着改版本号,先算算你欠了多少债
java·后端·ai编程