Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $YECBGYFECGEAFWHA as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2

Deprecated: imwpcache\f884414bce24ee67f\f73723ec7b1919fa5::__construct(): Implicitly marking parameter $BBWFDDBHHYHDXXAB as nullable is deprecated, the explicit nullable type must be used instead in /www/wwwroot/www.chuangxiangniao.com/wp-content/plugins/imwpcache-dist/build/f884414bce24ee67ff73723ec7b1919fa5.php on line 2
Python多进程中如何使用锁保证共享变量的原子操作?_创想鸟

Python多进程中如何使用锁保证共享变量的原子操作?

python多进程中如何使用锁保证共享变量的原子操作?

分享多进程操作共享变量的原子操作

在 python 多进程处理中,协调多个进程同时访问共享变量要保持原子性十分关键。为了解决这个问题,我们可以使用 concurrent.futures 模块中的 lock 对象。

1. 创建 manager 和 lock

我们首先创建一个 manager 对象,它允许多个进程共享数据。然后,我们创建一个 lock 对象,它将用于保护对共享变量的访问。

立即学习“Python免费学习笔记(深入)”;

2. 使用锁进行原子操作

在进程中操作共享变量时,我们可以使用 with 语句将 lock 作为上下文管理器。这将确保每次共享变量被更改时只允许一个进程访问它,从而保持原子操作。

修正后的代码示例:

from concurrent.futures import ProcessPoolExecutorimport ctypesfrom multiprocessing import Manager, Lockimport os# 创建 Manager 和 Lockmanager = Manager()m = manager.Value(ctypes.c_int, 0)lock = manager.Lock()def calc_number(x: int, y: int, _m, total_tasks: int, _lock):    # 模拟耗时任务函数    # 模拟耗时计算    res = x ** y        # 用锁来保证原子操作    with _lock:        _m.value += 1        current_value = _m.value        # 当总任务数量和_m.value相等的时候, 通知第三方任务全部做完了    if current_value == total_tasks:        print(True)        print(f"m_value: {current_value}, p_id: {os.getpid()}, res: {res}")def main():    # 任务参数    t1 = (100, 200, 300, 400, 500, 600, 700, 800)    t2 = (80, 70, 60, 50, 40, 30, 20, 10)    len_t = len(t1)    # 多进程执行任务    with ProcessPoolExecutor(max_workers=len_t) as executor:        for x, y in zip(t1, t2):            executor.submit(calc_number, x, y, m, len_t, lock)if __name__ == "__main__":    main()

这将确保多个进程每次只修改共享变量 m_value,从而实现原子操作。

以上就是Python多进程中如何使用锁保证共享变量的原子操作?的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1353795.html

赞 (0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
多进程编程中,如何保证共享变量的原子操作?
上一篇 2025年12月13日 17:59:14
Python多进程共享变量如何保证原子操作?
下一篇 2025年12月13日 17:59:32

相关推荐

发表回复

登录后才能评论
关注微信