I'm curious on how would one accomplish event driven programming from a language like python (or other, but for simplicity sake, python will do.). By that I mean providing a system that allow programmer to hook functions to certain events, and fire those events when triggered. (Basically the APIs behind all the GUI toolkits that connects events to functions, and how they recognize events in a main loop).

What I'm thinking right now is a while loop in python in a separate thread that will pick up events as they are triggered (checking conditions). However that seems inefficient.

Any thoughts/example code?

You are right that checking is terribly inefficient. Use messaging instead of checking. (When an event happens, make that system send a notification to the systems waiting on it.)

There are packages for event systems out there. I can't recommend one, but search and check out the source. You might find one you like or you might get ideas for writing one of your own.

I think you misunderstood my question. I'm wondering how you can get a system to "wait" for events.

I think you misunderstood my question. I'm wondering how you can get a system to "wait" for events.

A simple way to wait for events in a thread is to use a Condition object and its wait method

cond = Threading.Condition()

def mainloop():
    "This function is executed by the waiting thread"
    cond.acquire()
    try:
        while True:
            cond.wait() # the thread sleeps until the condition is notified
            if event_happened():
                handle_event()
    finally:
        cond.release()

def in_other_thread():
    ...
    create_an_event()
    cond.acquire()
    cond.notify()
    cond.release()
    etc()

You can also use a Queue.Queue instance and call its get() method. The method blocks until there is something in the queue. Then other threads put() events in the queue.

Edited 6 Years Ago by Gribouillis: n/a

Interesting, but how is the .wait() implemented? Or is that not possible in python?

This is platform dependent. See the sleep function in timemodule.c for example. In C, the function select() called with the first 4 arguments 0 waits ( select(0,0,0,0,timeout) ). In any case, waiting behaviour is obtained by calling underlying C functions which wait.

Edited 6 Years Ago by Gribouillis: n/a

Would this be something like the actual implementation of wait?

def wait(time_lapse):
	time_start = time.time()
	time_end = (time_start + time_lapse)
 
	while time_end > time.time():
		pass

In Python, It Just Works! (TM)

Don't worry about it.

If you must know how wait works you can read the source in threading.py or the multiprocessing source files.

This article has been dead for over six months. Start a new discussion instead.