2

I read a lot of about multiprocessing, threading but still i have problem with simple thing. I have 2 functions. I want call one by another and move one (this called function can't slow me up).

Example

def main():
    print("my operations")
    Thread(target=child(), args=()).start()
    print("rest operations")


def child():
    #here are some operations that takes 3 seconds
    print("background operations")

The point is that operations from child function can not slow me down. I want to just call that function and move on. So I want output like that:

my operations
rest operations
background operations

But doing this using Thread(target=child(), args=()).start() looks like

my operations
#then call child function wait 3 seconds
background operations
rest operations

There is and option to do what I want ?

2
  • sleep stops THE ENTIRE PROGRAM not just the thread it was called on. as an alternative you can use async programming
    – Nullman
    Commented Feb 3, 2021 at 9:02
  • this sleep is just for showing the problem I will edit it. @Nullman look now
    – KyluAce
    Commented Feb 3, 2021 at 9:03

2 Answers 2

8

When you do

Thread(target=child(), args=()).start()

you are calling child on the main thread, and then passing the result as the target! You want to pass the child function itself, not the result of calling it:

Thread(target=child, args=()).start()
3
  • so how should I do that ?
    – KyluAce
    Commented Feb 3, 2021 at 9:30
  • 1
    Lite i showed you; target=child, not target=child(). Commented Feb 3, 2021 at 10:33
  • sorry i didn't noticed difference.
    – KyluAce
    Commented Feb 3, 2021 at 10:38
1

python threads are not concurrent, at least not in CPython, because of the GIL(Global Interperter Lock). Threads will run one at a time and will switch between themselves according to several rules, like waiting for IO (like a web request for instance) or if the thread has been running for too long (15ms iirc).
You don't really have a good way to force a thread switch so its not as simple to demonstrate race conditions the way you are trying to do it. Here is a nice blog post talking about it with some examples

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.