Best practice for asynchronous c api design -
i'm design c api functionality , make asynchronous exposed functionality may take time. using blocking api not idea user of api need make many simultaneous calls.
what right way design interface can notify user asynchronous operation has completed?
i can think of several different approaches, can't aware of best practices this. have experiences similar api:s?
in example, intention return int containing answer.
callback function:
typedef void (*callback_function)(int, void *); /* calls callback function answer , cookie when done */ error_code dosomething(callback_function, void *cookie);
polling:
error_code dosomething(void *cookie); /* blocks until call has completed, returns answer , cookie */ error_code waitforsomething(int *answer, void **cookie);
platform specific event queue
/* windows version, api calls postqueuedcompletionstatus when done */ error_code dosomething( handle hiocompletionport, ulong_ptr dwcompletionkey, lpoverlapped lpoverlapped );
users of api typically event-driven, designs below not going idea.
futures:
/* external dummy definition future */ struct future_impl { int unused; }; typedef future_impl *future; /* initializes future, can waited on later */ error_code dosomething(future *future); /* blocks until result available */ error_code waitforsomething(future future, int *answer);
platform specific "futures"/events:
/* windows version, api signals event when done */ error_code dosomething( handle hevent, int *answer ); /* can waited on using waitformultipleobjects, has limit on how many events can used */
i go callback function basic building block. i've seen design used many times , works. void pointer allows pass around context while callback parameter error code. can build other layers on top of this, e.g. state machine, event queue or passing os synchronization objects in context.
Comments
Post a Comment