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()
我有一个称为队列的全局类。队列的数据在2个不同的功能之间共享,但不起作用。
为什么函数“ get_tasks()”中的队列始终等于1?我认为队列是线程安全的,可以在不同进程之间共享?
创建新流程时,它会复制当前环境并在新环境中重新创建它。创建过程后,将不再共享这些全局变量。
但是,该multiprocessing
库包含了流程之间进行通信的方式
您仍然可以使用队列,但是必须使用多处理队列,而不要使用本地队列。在Queue
后台,每个进程都有自己的对象,它们只是在进程之间来回传递信息以同步队列状态。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句