Sharing a Queue instance between different modules

2024/11/18 23:39:32

I am new to Python and I would like to create what is a 'global static variable', my thread-safe and process-safe queue, between threads/processes created in different modules. I read from the doc that the concept of a global variable is created using a third module, that I will call as cfg, which defines and initializes my global queue. I have a problem sharing the instance of this objects between my modules because I tried to print the repr() function over the shared queue imported from the cfg module, inside my other modules that import it, and it shows that they are different instances. It seems that every time I try to import a module a new instance is created and passed to the module who imports it.

Main.py:

import GatewayManager
if __name__ == '__main__':GatewayManager.initialize()doSomething()

GatewayManager.py:

import multiprocessing
import queue
import threadingdef initialize():# Multiprocessing or Threadingglobal isMonoCPUisMonoCPU = multiprocessing.cpu_count() == 1global sharedQueuesharedQueue = multiprocessing.Queue() if not isMonoCPU else queue.Queue()print("gateway: ", sharedQueue.__repr__())

otherModules.py:

import GatewayManager# Some module write on the queue
GatewayManager.sharedQueue.put(variable)# Some read from the queue
GatewayManager.sharedQueue.get()
print("driver: ", GatewayManager.sharedQueue.__repr__())
Answer

A multiprocessing.Queue is shared between the process that creates it (let's call it "Parent") and processes created by Parent (let's call them "Children").

Here is an example of some processes that do not have this relationship:

$ python myprogram.py &
$ python myprogram.py &

The shell is the Parent of these two Children. The shell did not create the multiprocessing.Queue, though, so it will not be shared by the two children. Instead, they will each create their own. This may be shared with their children but not with each other.

You can easily observe this behavior:

$ cat queuedemo.py 
from time import sleep
from os import getpid
from sys import argvfrom multiprocessing import Queueq = Queue()if argv[1:]:q.put(getpid())sleep(60)
else:print(getpid(), q.get())
exarkun@baryon:/tmp/queue$ python queuedemo.py foo & python queuedemo.py 
[1] 28249

The second process never manages to read anything from the queue. However, if you give the two process the Parent-Child relationship...

$ cat queuedemo.py 
from os import getpidfrom multiprocessing import Queue
from multiprocessing.process import Processq = Queue()
q.put(getpid())def child():print(getpid(), q.get())p = Process(target=child)
p.start()
p.join()
exarkun@baryon:/tmp/queue$ python queuedemo.py 
(28469, 28467)
exarkun@baryon:/tmp/queue$ 

Notice that the q.get() call succeeds and that the pid put into the queue is different from the pid of the process that gets it out.

Somewhat necessarily, this also extends to processes with Parent-Descendant and Sibling relationships.

So:

  • Globals are only shared within a single process
  • The multiprocessing module provides tools to share state between processes that are properly related to each other.

If you want to share state between processes without this relationship, there are a variety of other options - and the best one will depend a bit more on what kind of state you have to share and what your sharing patterns look like (neither of which you've included in your question).

https://en.xdnf.cn/q/118613.html

Related Q&A

Square a number with functions in python [duplicate]

This question already has answers here:What does it mean when the parentheses are omitted from a function or method call?(6 answers)Closed last year.This is an extremely easy question for Python. Its…

Changing the cell name

I have a file that contains the following:NameABCD0145ABCD1445ABCD0998And Im trying to write a cod that read every row and change the name to the following format:NameABCD_145ABCD_1445ABCD_998keeping i…

Procfile Heroku

I tried to deploy my first Telegram chatbot (done with Chatterbot library) on Heroku. The files of my chatbot are: requirements (txt file) Procfile (worker: python magghybot.py) botusers (csv file) Mag…

How do i loop a code until a certain number is created?

This task is to determine the difference between two attributes, strength and skill, from game characters. The process for this is:Determining the difference between the strength attributes. The differ…

Finding the longest list in given list that contains only positive numbers in Python [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed l…

How to create multiple VideoCapture Objects

I wanted to create multiple VideoCapture Objects for stitching video from multiple cameras to a single video mashup.for example: I have path for three videos that I wanted to be read using Video Captur…

How to read Data from Url in python using Pandas?

I am trying to read the text data from the Url mentioned in the code. But it throws an error:ParserError: Error tokenizing data. C error: Expected 1 fields in line 4, saw 2url="https://cdn.upgrad.…

Testing multiple string in conditions in list comprehension [duplicate]

This question already has answers here:How to test multiple variables for equality against a single value?(31 answers)Closed 6 years ago.I am trying to add multiple or clauses to a python if statement…

Filter range from two dates in the same query Django/Python

I need the result from a query that filters two dates from the same model. I need to get in the result 5 days (today plus 4 days) from original date and sale from target date (today plus 4 more days) b…

Python While/For loop

how can I make this into a while loop and output the same thing????for x in range(56,120) :if (x < 57) :summation = 0summation = x + summationif (x == 119) :print (“Sum of integers from 56 to 1…