【问题标题】:Python shared queue - 2 different threadsPython共享队列 - 2个不同的线程
【发布时间】:2018-03-06 00:14:01
【问题描述】:
import time
from flask import Flask, jsonify
from multiprocessing import Process, Value

app = Flask(__name__)

class Queue:
    def __init__(self):
        self.items = []

    def isEmpty(self):
        return self.items == []

    def enqueue(self, item):
        self.items.insert(0,item)

    def dequeue(self):
        return self.items.pop()

    def size(self):
        return len(self.items)

tasks = [
   {
      'id': 1,
      'title': u'Buy groceries',
      'description': u'Milk, Cheese, Pizza, Fruit, Tylenol',
      'done': False
   },
   {
      'id': 2,
      'title': u'Learn Python',
      'description': u'Need to find a good Python tutorial on the web',
      'done': False
   }
]

q = Queue()

@app.route('/todo/api/v1.0/tasks', methods=['GET'])
def get_tasks():

   q.enqueue('cat')
   print("Size: " + str(q.size()))

   return jsonify({'tasks': tasks})


def record_loop(loop_on):
   while True:
      if loop_on.value == True:
         print("loop running")

         q.enqueue('dog')
         print("Size: " + str(q.size()))

      time.sleep(1)


if __name__ == "__main__":
   recording_on = Value('b', True)
   p = Process(target=record_loop, args=(recording_on,))
   p.start()
   app.run(debug=True, use_reloader=False)
   p.join()

我有一个名为 queue 的全局类。队列的数据在 2 个不同的函数之间共享,但它不起作用。

为什么函数'get_tasks()'中的队列大小总是等于1?我认为队列是线程安全的,它们可以在不同的进程之间共享?

【问题讨论】:

  • 大小对我来说并不总是 1。每次record_loop 运行时它都会增加。最终目标是什么?
  • 创建一个在这两个函数之间共享的任务队列。他们需要访问同一个队列。为什么它不改变 'get_tasks()' 函数的大小?

标签: python flask concurrency queue


【解决方案1】:

当您创建一个新进程时,它会复制当前环境并在新环境中重新创建它。创建流程后,这些全局变量将不再共享。

但是,multiprocessing 库包含了communicate between processes 的方法

您仍然可以使用队列,但您必须使用多处理 Queue 而不是您自己的。在底层,每个进程都有自己的 Queue 对象,它们只是在进程之间来回传递信息以同步队列状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-03
    • 1970-01-01
    • 2011-05-21
    • 1970-01-01
    • 2016-03-10
    相关资源
    最近更新 更多