Python线程和原子操作 [英] Python threads and atomic operations

查看:369
本文介绍了Python线程和原子操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用同步的stop()方法实现线程.

I want to implement a thread with a synchronous stop() method.

我看过这样的版本:

class Thread1:
    def __init__(self):
        self._stop_event = threading.Event()
        self._thread = None

    def start(self):
        self._thread = threading.Thread(target=self._run)
        self._thread.start()

    def stop(self):
        self._stop_event.set()
        self._thread.join()

    def _run(self):
        while not self._stop_event.is_set():
            self._work()

    def _work(self):
        print("working")

但是我已经读到原子操作是线程安全的,而且在我看来,无需Event就可以完成.所以我想出了这个:

But I've read that atomic operations are thread safe and it seems to me that it can be done without Event. So I came up with this:

class Thread2:
    def __init__(self):
        self._working = False
        self._thread = None

    def start(self):
        self._working = True
        self._thread = threading.Thread(target=self._run)
        self._thread.start()

    def stop(self):
        self._working = False
        self._thread.join()

    def _run(self):
        while self._working:
            self._work()

    def _work(self):
        print("working")

它认为在C语言中类似的实现将被认为是错误的,因为编译器可以将_working放入寄存器(甚至进行优化),并且工作线程永远不会知道变量已更改.这样的事情会在Python中发生吗?这个实现正确吗?我并不是要完全避免发生事件或锁定,只是想了解这种原子操作的事情.

It think that similar implementation would be considered incorrect in C, because compiler can put _working to a register (or even optimize out) and the working thread would never know that the variable has changed. Can something like that happen in Python? Is this implementation correct? I don't aim to avoid events or locks altogether, just want to understand this atomic operations thing.

推荐答案

据我所知,它在Python中也是不正确的,因为_working仍可以通过其他方式或其他方式进行注册或优化可能发生的事情会改变它的价值.对该字段的读写可以由处理器任意重新排序.

As far as I can tell it is also incorrect in Python, as _working can still be put in register or optimized in some other way, or some other thing may happen that would change it's value. Reads and writes th this field could be arbitrarily reordered by the processor.

可以说,在多线程世界中,您实际上不会问:为什么这不起作用,而是为什么要保证这种作用.

Well lets say that in multithreading world you shouln't really ask: Why this shouldn't work, but rather Why this is guarranteed to work.

前面已经说过,由于 GIL ,在大多数情况下,多线程在CPython中要容易一些.保证:

Having said that in most cases multithreading is a little bit easier in CPython, because of GIL that guarantees that:

  • 在任何给定时间仅执行一个解释器命令.
  • 强制经常在线程之间进行内存同步.

请记住,GIL是一个实现细节,如果有人不使用它重写CPython,它可能会消失.

Bear in mind that GIL is a implementation detail, that might go away if someone rewrites CPython without it.

还要注意,它应该在任何实际系统中都以这种方式实现.

Also note that the fact that it should implement it this way in any real system.

这篇关于Python线程和原子操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆