tags:

views:

65

answers:

3

Hello,

gcc 4.4.2 c89

I have a function that has to run (config_relays). It make a call to a API function called set_relay, then the code has to wait before continuing until the event for set_relay event has completed. The set_relay is any Async call.

i.e.

void run_processes()
{
    switch()
    {
        case EV_RELAY_SET:
        break;
    }
}


void config_relays()
{
    set_relay();

    /* Wait until EV_RELAY_SET has fired */
    /* Cannot do init_relay until set_relay event has fired - has to block here */
    init_relay();
}

I guess I could put the init_relay() in the switch. However, that event is used for other things and not just for initializing the relay. I would really like to handle everything in the config_relays function.

In C# you can do this by using autoreset. Does C have anything like that.

Many thanks for any advice,

A: 

It depends on what threading library you are using and how the asynchronous method is called. If you are on Windows, there are auto-reset events in the Windows API that you can use. See the CreateEvent API. If you are on unix/linux you can look into condition variables in pthreads. Unfortunately pthreads doesn't have auto-reset events, because they are very hard to use in a race-condition-free way.

When choosing your waiting strategy you also have to take into consideration how the asynchronous call is done. Is it on another thread? Is it done through signal handling? Some other asynch mechanism which "borrows" the main thread? If the call is done by "borrowing" the main thread, you have to make sure that your waiting strategy does not stop the thread from being used to perform the asynch call.

Anders Abel
+1  A: 

1) You can use OS specific API's like createEvent or pthread condition variable to wait on and signal it when set_relay() is completed.

2) Polling approach. Poll periodically to see set_relay() is completed, else sleep for few seconds and retry.

kumar
I am compiling on Redhat. So would be using pthreads. Option 2, I was thinking about polling in a while loop and having a condition set (global variable) in the event and testing if this condition is true. 1) I am interested in option 1.
robUK
Good, the polling aproach is bad, very bad. Never ever design a system with the poll/sleep scheme. It may become a bottleneck...
Ernelli
+2  A: 
Ernelli