Search code examples
pythonmultithreadingblocking

Creating a new thread that _really_ runs in parallel


I have the following Code in a class:

def persistDBThread(self):
    while True:
        Thread(target=self.__persistDB)
        time.sleep(10)

def  __persistDB(self):
    with open(self.authDBPath, 'w') as outfile:
        json.dump(self.authDB, outfile)

The thread gets started in the __ main__ but as soon as I start this thread it is actually blocking in the main execution.

Why is this? I know about the GIL - it's all in the same process. Task switching happens in the same process in micro-thread, but why doesn't it switch back?

Thanks!

Sorry for even asking:

def persistDBThread(self):
    Thread(target=self.__persistDB).start()


def  __persistDB(self):
    while True:
        time.sleep(10)
        outfile = open(self.authDBPath, 'w')
        json.dump(self.authDB, outfile)

Solution

  • You are calling __persistDB too soon. Use target=self.__persistDB with no parentheses at the end. When you include the parentheses, you are calling the function before the threading call is made. Without the parentheses, you pass the function as an argument to be called later.

    You will then need to call the resulting Thread object's start method. This is all described in the documentation, which you should read.

    Also, don't run that in a while True loop. That will just create endless numbers of threads as you call Thread again and again. Google or search StackOverflow for "Python threading example" to find many examples of the right way to use the threading module, e.g., here.