Search code examples
clinuxlibevent

When does a C code interrupt in event driven programming mode ?


I'm new to c, and event driven programming.

We are using libevent to develop

  1. how does interrupt work, and when does it happen?
  2. Will it interrupt in the middle of a function, or does it always interrupt in the end of a function?

for example,

extern int arr[100];

void some_func1() {
    int flag;
    // do something to change flag
    if(flag == 0) {
        update1(arr);
    }else if(flag == 1) {
        update2(arr);
    }
}

void some_func2() {
    // print something based on arr
}

some_func1 will be called when event1 happens, and some_func2 will be called if event2 happens.

case 1.
First event1 occurs then some_func1 be called and finished, so arr is updated correctly, then event2 occurs, and print is ok

case 2.
First event1 occurs then some_func1 be called, and in the middle of it, another event1 is called, then arr is messed up.

  1. Will case 2 happen? Is it possible to make some_func1 an atomic function?

Solution

  • From the doc:

    Dispatching events.

    Finally, you call event_base_dispatch() to loop and dispatch events. You can also use event_base_loop() for more fine-grained control.

    Currently, only one thread can be dispatching a given event_base at a time. If you want to run events in multiple threads at once, you can either have a single event_base whose events add work to a work queue, or you can create multiple event_base objects.

    So, if you've got one thread and one event_base then event_base_dispatch()/event_base_loop() in this thread call handler functions one by one.

    If you've got two threads and two event_base (one in each thread) then they work independently. The first event_base handles its events one by one in the first thread; the second event_base handles its events one by one in the second thread.

    (I haven't used libevent, but that's how generally the event loops work)