Reputation: 3549
From what I have read, callbacks are non-blocking. The function passed as a callback begins to execute even as the enclosing function has not completed. But I am missing something. In this example:
def func1(x, callback):
print(x)
for _ in range(100000000):
continue
print("done counting to hundred million")
callback()
def func2():
for _ in range(10000000):
continue
print("counted to 10 million")
func1("starting to count to hundred million",func2)
func1 counts to a hundred million (to simulate a lagging network socket or other process). I thought func2 would execute before func1 completes, but it does not. Obviously I have misunderstood the asynchronous nature of callbacks. Are they asynchronous and how am I missing this?
Upvotes: 1
Views: 1261
Reputation: 94891
No, callbacks are not asynchronous by default. Many asynchronous APIs use callbacks, but callbacks by their nature do not imply asynchronous behavior. In your example, you're just passing the func2
function object to func1
like you would any other type of object, and then you actually call it in a synchronous way after iterating over your range
object, the same way you would call a normal function. The fact that you passed the function object as an argument to func1
has no special meaning.
You're probably thinking of asynchronous APIs that take callbacks as arguments here, like multiprocessing.Pool.apply_async
. In that case, multiprocessing.Pool
is designed to run a function in a worker process, and then asynchronously execute a callback
in a background thread in the main process when the worker process completes. This is done using logic built into multiprocessing.Pool
though, it doesn't just magically happen because the function takes an argument called callback
.
Upvotes: 2