A bug regarding sys.run_in_thread

We tried to use threads in our code but there is a bug. It runs the function in the parameters and then it crashes. Can you check it out?

Link:
https://www.robotmesh.com/studio/6055298dd07e4038a6245153#

Thanks

Yes, you cannot pass arguments to a function being run in a thread. As it takes only the name of a function, using the function argument syntax will do exactly what you told it to: run the function. The crash is because you are passing the return value of that function to run_in_thread. If you don’t have a return value, then it’s None, which run_in_thread won’t like.

If you want to call a class method in a thread, use a lambda:

class Foo:
    def __init__(self):
        self.bar = 1
    def printbar(self):
        print self.bar

a = Foo()

sys.run_in_thread(lambda: a.printbar())

>>> 1

The same trick also lets you use function parameters or class method parameters.

class Foo:
    def __init__(self):
        self.bar = 1
    def printbaz(self, num):
        print self.bar + num

a = Foo()

sys.run_in_thread(lambda: a.printbaz(20))

>>> 21

Here’s a V5 mimic project which shows this code in action, executing it in your browser using Javascript. Simply click “play” to run the code.