这个双端队列在 python 中是线程安全的吗? [英] Is this deque thread-safe in python?

查看:22
本文介绍了这个双端队列在 python 中是线程安全的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法确定以下双端队列是否是线程安全的.
简而言之,我创建了一个带有双端队列的类,它每 1 秒在一个新线程中显示其内容(因此它不会在打印时暂停主程序).
deque 是从主线程填充的,所以基本上应该有碰撞的机会.
然而,双端队列是使用类方法填充的,因此本质上它是从实例本身内部访问的,因此是从同一个线程中访问的.
这是简化的代码:

I can't decide whether the following deque is thread-safe.
In short, I've created a class with a deque that displays its contents every 1 sec in a new thread (so it won't pause the main program while printing).
The deque is filled from the main thread, so basically there SHOULD be a chance of collision.
HOWEVER, the deque is filled using a class method, so essentially it is accessed from within the instance itself, therefore from the same thread.
Here's the simplified code:

import threading
import time
from collections import deque

class MyQueue(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.q = deque()
        self.start()

    def run(self):
        # pop out queue items every 1 sec
        # (please ignore empty deque for now)
        while True:
            print self.q.popleft()
            time.sleep(1)

    def add_to_q(self, val):
        # this function is called from outside
        self.q.append(val)

# main
# fill the queue with values
qu = MyQueue()
for i in range(1:100):
    qu.add_to_q(i)

那么,虽然从队列中添加和删除项目是在实例内部进行的,但是否存在从实例外部调用添加函数的风险?

So, although adding and removing items from queue take place inside the instance, is there a risk due to the adding function being called from outside the instance?


由于我需要修改我的双端队列中的项目,我不得不使用双端队列.我要做的是:将()旋转到给定的项目,将其弹出,修改,将其推回并旋转()到其原始位置.
除非我找到一种方法来实现修改队列中的项目,否则我将不得不坚持使用 Deque


Since I need to modify items in my deque, I had to use Deque. What I do is: roatate() to the given item, pop it out, modify, push it back in and rotate() it back to its original position.
Unless I find a way of implementing modifying items in a Queue, I'll have to stick to Deque

推荐答案

Deque 是线程安全的 (http://docs.python.org/library/collections.html#deque-objects) 用于从相反侧追加和弹出.下面,文档只提到了 append() 和 popleft() 是线程安全的.

Deque is thread-safe (http://docs.python.org/library/collections.html#deque-objects) for appends and pops from opposite sides. Beneath here, the docs only mention that append() and popleft() are thread-safe.

队列本身有一个线程安全的实现.所以除非你有一些奇怪的需求,否则你应该使用它.

There is a thread-safe implementation of the Queue itself. So you should be using it unless you have some strange requirements.

这篇关于这个双端队列在 python 中是线程安全的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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