Implementing a singleton class and (b) locking issues?

I was wondering how to implement a singleton class after http://code.activestate.com/recipes/52558-the-singleton-pattern-implemented-with-python/ , but wondered about any (b) locking issues. My code should cache the SQL statements and execute all cached statements using cursor.executemany (SQL, list-of-params) when a certain number of cached items are reached, or a specific execution call is made by the user. It was supposed that the implementation of singleton support allows you to cache operators at the application level, but I'm m afraid I ll run (b) problems with locking.

Any thoughts?

+4
source share
4 answers

By avoiding lazy initialization, the lock problem will disappear. In the module in which your database connection is initialized, import the module that contains the singleton, and then immediately instantiate the singleton that is not stored in the variable.

 #Do Database Initialization import MySingleton MySingleton() #Allow threads to be created 
+1
source

Why don't you use the module directly (as stated earlier, models are Singletons). If you create a module, for example:

 # mymodule.py from mydb import Connection connection = Connection('host', 'port') 

you can use the import mechanism, and the connection instance will be the same everywhere.

 from mymodule import connection 

Of course, you can define a much more complex initialization of connection (perhaps by writing your own class), but the fact is that Python will only initialize the module once and provide the same objects for each subsequent call.

I believe that Singleton (or Borg) templates have very specific Python applications, and for the most part you should rely on direct import until proven otherwise.

+1
source

There should be no problem if you do not plan to use this instance of Singleton with multiple threads.

Recently, I ran into some kind of problem caused by the incorrect implementation of the cache reload mechanism - the cache data was first cleared and then filled. This works well on a single thread, but generates multithreading errors.

0
source

While you are using CPython - Global Interpreter Lock should prevent locking issues. You can also use the Borg pattern .

0
source

Source: https://habr.com/ru/post/1341419/


All Articles