如何在使用多处理进行无限循环编程时发出请求

时间:2019-07-01 12:26:08

标签: python multiprocessing python-multithreading

我有两个功能需要同时运行。 read_card需要无限循环,并等待新卡(它实际上是Nrf读取器),并且 将一些字符串添加到队列中,send_data假设从队列中获取值并通过请求库将其发送到服务器。当我不使用多处理功能时,一切正常。但是我想我需要并发。

这是我的两个功能。

def read_card(reader, configs):
    print("First started")
    while True:
        authorized_uid = reader.is_granted(reader.read())
        print("Waiting for card")
        #TODO:If not authorized in AccessList.txt look to the server
        if authorized_uid is not None:
            print(authorized_uid)
            open_door()
            check_model = CheckModel(configs.DeviceSerialNumber, authorized_uid)
            message_helper.put_message(check_model)

def send_data(sender):
    print("Second started")
    while True:
        message_model = message_helper.get_message()
        if message_model is not None:
            sender.send_message(message_model)

这是我的主要称呼方式

def main():
    download_settings()
    create_folders()
    settings = read_settings()
    accessList = get_user_list(settings)
    configure_scheduler(settings)  

    message_sender = MessageSender(client.check,client.bulk)

    reader_process = multiprocessing.Process(name = "reader_loop", target = read_card, args=(Reader(accessList, entryLogger),configs,))
    message_process = multiprocessing.Process(name = "message_loop", target = send_data, args=(message_sender,))
    reader_process.start()
    message_process.start()

if __name__ == '__main__':
    main()

这些用于调试。我打印了来自不同班级的put_messagesend_message

def send_message(self,model):
    print(model)
    return self.checkClient.check(model)

def put_message(self, message):
    print(message)
    self.put_to_queue(self.queue, message)
    self.put_to_db(message)

我希望在终端中看到一些对象名称,但是我只会在下面看到。另外阅读器也不起作用。

First started
Second started

我哪一部分做错了?

1 个答案:

答案 0 :(得分:0)

使用declare var Image: { new(width?: number, height?: number): HTMLImageElement; }; namespace n { const enum Image{i1, i2} let q: HTMLImageElement = new Image(); } 在进程之间进行通信。然后,当您在Queue中读取卡时,创建一个新作业并将其推入队列,然后将该作业放入处理器中并发送请求。

这是概念证明:

reader

打印:

from datetime import datetime
from multiprocessing import Process, Queue
from random import random
from time import sleep

import requests


def reader(q: Queue):
    while True:
        # create a job
        job = {'date': datetime.now().isoformat(), 'number': random()}
        q.put(job)
        # use a proper logger instead of printing,
        # otherwise you'll get mangled output!
        print('Enqueued new job', job)
        sleep(5)


def client(q: Queue):
    while True:
        # wait for a new job
        job = q.get()
        res = requests.post(url='https://httpbin.org/post',
                            data=job)
        res.raise_for_status()
        json = res.json()
        print(json['form'])


if __name__ == '__main__':
    q = Queue()
    reader_proc = Process(name='reader', target=reader, args=(q,))
    client_proc = Process(name='client', target=client, args=(q,))

    procs = [reader_proc, client_proc]
    for p in procs:
        print(f'{p.name} started')
        p.start()
    for p in procs:
        p.join()