Skip to content Skip to sidebar Skip to footer

How To Pass A Boolean By Reference Across Threads And Modules

I have a boolean that I want to pass to different threads that are executing methods from different modules. This boolean acts as a cancellation token so if set, the thread should

Solution 1:

When you do this:

thread2 = Thread(target = module2.method2, args (on_input, cancellationToken, ))

You're essentially passing the value False for the 2nd argument to the thread method.

But when you do this after that:

cancellationToken = True

You're replacing the reference represented by cancellationToken, but not the value that was originally passed to thread2.

To achieve what you want to do, you'll need to create a mutable object wrapper for your cancellation state:

classCancellationToken:
   def__init__(self):
       self.is_cancelled = Falsedefcancel(self):
       self.is_cancelled = True

cancellationToken = CancellationToken()

thread2 = Thread(target = module2.method2, args (on_input, cancellationToken, ))

# then later on
cancellationToken.cancel()

Your thread code becomes:

defmethod2(on_input, cancellationToken):
    while(True):
        if(cancellationToken.is_cancelled):
            return
        ...
        on_input(...)

Post a Comment for "How To Pass A Boolean By Reference Across Threads And Modules"