Home > OS >  What happens with python threads stored as class parameters that get overwritten? And why?
What happens with python threads stored as class parameters that get overwritten? And why?

Time:09-01

I made the following code:

#!/usr/bin/python3

import threading, time

class Threader():
    def __init__(self):
        self.var = 1
    
    def create_threads(self):
        self.mythread=threading.Thread(target=self.do_things, daemon=True)
        self.mythread.start()

    def do_things(self):
        time.sleep(0.5)
        self.var=self.var 1

mobject = Threader()
mobject.create_threads()
mobject.create_threads()
mobject.create_threads()

time.sleep(3)
print(mobject.var)

Which prints the number 4 in the screen. I made it to test the assumption that, since the time that python takes to call mobject.create_threads() is less than 0.5 seconds, the mythread parameter would get overwritten and then the thread execution would stop before doing the self.var =1 operation.

This assumption is clearly wrong: all threads were executed until the end, adding 1 to self.var. Why? In other words: when a thread is instantiated as a class parameter and the parameter gets overwritten as anything else, is there any risk that the thread will stop without getting to the end of it? If yes or no, why?

CodePudding user response:

create_threads runs instantaneously and returns. It is not a threaded function -- it is entirely synchronous. Yes, you are overwriting mobject.mythread, but since you don't use it after that function returns, it doesn't matter.

  • Related