Using Multithreaded queue in python the correct way?

落花浮王杯 提交于 2019-12-04 00:49:35

While its possible to create a new independent thread for the queue, and process that data separately the way you are doing it, I believe it is more common for each independent worker thread to post messages to a queue that they already "know" about. Then that queue is processed from some other thread by pulling messages out of that queue.

Design Idea

The way I invision your application would be three threads. The main thread, and two worker threads. 1 worker thread would get requests from the database and put them in the queue. The other worker thread would process that data from the queue

The main thread would just waiting for the other threads to finish by using the thread functions .join()

You would protect queue that the threads have access to and make it thread safe by using a mutex. I have seen this pattern in many other designs in other languages as well.

Suggested Reading

"Effective Python" by Brett Slatkin has a great example of this very question.

Instead of inheriting from Queue, he just creates a wrapper to it in his class called MyQueue and adds a get() and put(message) function.

He even provides the source code at his Github repo

https://github.com/bslatkin/effectivepython/blob/master/example_code/item_39.py

I'm not affiliated with the book or its author, but I highly recommend it as I learned quite a few things from it :)

Burkely91

I like this explanation of the advantages & differences between using threads and processes - ".....But there's a silver lining: processes can make progress on multiple threads of execution simultaneously. Since a parent process doesn't share the GIL with its child processes, all processes can execute simultaneously (subject to the constraints of the hardware and OS)...."

He has some great explanations for getting around GIL and how to improve performance

Read more here:

http://jeffknupp.com/blog/2013/06/30/pythons-hardest-problem-revisited/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!