mountain surrounded with fog

What Exactly a Callback Function Means




What is Callback?

For many starters, a callback function may be hard to understand. And it seems that a callback function is unnecessary in our code, but it can be quite useful once you learn what callback means and how to use it in your code.

Let’s say you write a programme which has two threads, the main thread deal with any user logic and another thread constantly processing data and has no obvious connection with the user logic. For example, the data is a random number generate according to UTC time, and the user get a random number whenever they press a button. Of cause you can define a get() function which return the random number. But because the random number generator changes frequently, the user may not get the right number if they press a button for too long, cause the number already change many times during the press and release operation. And to deal with the button’s logic is a pain in the head.

At this point, a callback function may comes in handy. Let’s start with real python example!

Python
import time
import random
from threading import Thread

class RandomNumberGenerator(Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.random_number = None
        self.stop_event = threading.Event()

    def run(self):
        while not self.stop_event.is_set():
            self.update_random_number()
            time.sleep(0.01)  # Wait for 0.01 second

    def update_random_number(self):
        # Get current UTC time as a seed
        seed = int(time.time())

        # Set the seed for the random number generator
        random.seed(seed)

        # Generate a random number
        self.random_number = random.randint(1, 100)

    def stop(self):
        self.stop_event.set()

Now, if we want to use a callback function, we should define a set_callback() function. So that we can define what we want without having to modify the RandomNumberGenerator().

Python
import time
import random


class RandomNumberGenerator(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)
        self.random_number = None
        self.stop_event = threading.Event()
        self.callback = None

    def run(self):
        while not self.stop_event.is_set():
            self.update_random_number()
            time.sleep(0.01)  # Wait for 0.01 second

    def update_random_number(self):
        # Get current UTC time as a seed
        seed = int(time.time())

        # Set the seed for the random number generator
        random.seed(seed)

        # Generate a random number
        self.random_number = random.randint(1, 100)

        if self.callback:
            self.callback(self.random_number)

    def stop(self):
        self.stop_event.set()

    def set_callback(callback):
        self.callback = callback

How to use it?

Below is how we can use it. This means when a button is pressed, it will get the number from random number generator and print it in command line. By using a callback function, you can avoid the possibility of numbers being tampered with.

Python
# This is the callback function where you can put your user logic
def callback(number):
    if on_button_pressed():
        print(number)

# Your code here
def main():
    // ...
    
if __name__ == "__main__":
    rng = RandomNumberGenerator()

    # Start the random number generation in a separate thread
    rng.start()
    
    # Setup callback function
    rng.set_callback(callback)
    
    main()



Leave a Reply

Your email address will not be published. Required fields are marked *