Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 线程-中断循环的sentinel值或事件_Python_Multithreading_Python 3.x_Thread Safety_Python Multithreading - Fatal编程技术网

Python 线程-中断循环的sentinel值或事件

Python 线程-中断循环的sentinel值或事件,python,multithreading,python-3.x,thread-safety,python-multithreading,Python,Multithreading,Python 3.x,Thread Safety,Python Multithreading,我可以想出两种方法来打破Python线程中的循环,下面是一些简单的例子: 1-使用sentinel值 2-使用事件 在Python文档中,它讨论了事件,但没有讨论更简单的“sentinel值”方法,我在堆栈溢出的许多线程回答中看到了这种方法 使用sentinel值有什么缺点吗 具体来说,它会导致错误吗?我从来没有遇到过错误,但我想,如果你试图在while循环读取哨兵的同一时刻更改哨兵的值,那么可能会出现故障,或者CPython GIL可能会在这种情况下救我一命。什么是最安全的做法?如果您查看事件

我可以想出两种方法来打破Python线程中的循环,下面是一些简单的例子:

1-使用sentinel值

2-使用事件

在Python文档中,它讨论了事件,但没有讨论更简单的“sentinel值”方法,我在堆栈溢出的许多线程回答中看到了这种方法

使用sentinel值有什么缺点吗


具体来说,它会导致错误吗?我从来没有遇到过错误,但我想,如果你试图在while循环读取哨兵的同一时刻更改哨兵的值,那么可能会出现故障,或者CPython GIL可能会在这种情况下救我一命。什么是最安全的做法?

如果您查看事件来源,您会发现您正在使用的功能对您没有任何价值:

class Event:
    def __init__(self):
        self._cond = Condition(Lock())
        self._flag = False

    def is_set(self):
        return self._flag

    def set(self):
        with self._cond:
            self._flag = True
            self._cond.notify_all() # No more-value, because you are not using Event.wait
所以在你的例子中,事件只是一个没有实际用途的哨兵值的花式包装器,它也会将你的操作时间降低一点点


事件只有在使用其等待方法时才有用。

从my mempry中,事件类只是一个sentinel值加上一个锁,以确保线程安全。看看来源。我看了一下来源,这似乎是正在发生的事情,尽管有些事情超出了我的头脑。但我的问题仍然适用,一个更简单的sentinel值不是线程安全的,或者假设使用Python实现可以吗?如果您在线程中使用select.select进行I/O,您应该检查[.Sockets也不错,如果你想传递一些基本的控制命令而不是退出的话。@Hinni-有趣的是,我不知道你能做到这一点!对不起,我弄乱了URL格式。它是socket.socketpair。我经常将它与队列或deque一起使用。因此,socket只需写一个字符,而不是你看队列。
from threading import Thread, Event
from time import sleep

class SimpleThread(Thread):

    def __init__(self):
        super(SimpleThread, self).__init__()

        self.stoprequest = Event()

    def run(self):
        while not self.stoprequest.isSet():
            sleep(1)
            print('loop completed')

    def join(self, timeout=None):
        self.stoprequest.set()
        super(SimpleThread, self).join(timeout)

simpleinstance = SimpleThread()
simpleinstance.start()
sleep(5)
simpleinstance.join()
class Event:
    def __init__(self):
        self._cond = Condition(Lock())
        self._flag = False

    def is_set(self):
        return self._flag

    def set(self):
        with self._cond:
            self._flag = True
            self._cond.notify_all() # No more-value, because you are not using Event.wait