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

相关推荐
\光辉岁月/1 小时前
javaSE8-新特性-Stream&Option
java·stream·option
ZoeLandia1 小时前
React03:useState 与不可变更新
前端·react.js·typescript·react
zzu123zsw1 小时前
把条件校验收敛到枚举接口:Spring Boot 统一断言模式与零污染异常切面工程化
java·spring boot·后端·架构设计
SL_staff1 小时前
计划系统落地难?从开发者视角重构执行入口体验
java·开源·全栈
m0_敲代码的彭于晏1681 小时前
OpenCode 2.0 智能编程效果全景展示
人工智能·python·语言模型
蒲公英内测分发1 小时前
智能手表卖出去后,包装、说明书和官网里的 App 下载入口怎么统一?
前端·人工智能·测试工具·智能家居·智能硬件·智能手表
溪语流沙1 小时前
【Web全栈进阶】监控与告警:线上系统的“体检报告”
前端·vue.js·python·fastapi
鬼手点金1 小时前
单轮对话:最简单的 API 调用
java·服务器·前端·javascript·react.js·servlet·tomcat
蜡笔羊驼1 小时前
ModuleNotFoundError: No module named ‘torchvision.transforms.functional_tensor‘
linux·人工智能·python