c++ - linux shared library to support multi threaded application callbacks -
i need create shared library exposes set of apis used multiple processes might have more 1 thread apis called.
this shared library in turn uses 3rd party shared library need register callback. 3rd party library calls registered callback different thread.
i want know how block thread on call of api defined in library , release when callback 3rd party library. locking should not block other thread calling same api...!
i'm using pthread library create library.
psudo code:
my library:
int lib_init() { register_callback(callback); } int lib_deinit() { unregister_callback(); } int callback(void *) { <unblock functions> } int function1(int, int) { perform_action(); <should block till callback 3rd party library> } int function2(char, char) { perform_action(); <should block till callback 3rd party library> }
3rd party library:
int register_callback(callback) { .... launch_thread(); .... } int unregister_callback() { .... terminate_thread(); .... } int perform_action() { /* queue action */ } void* thread(void*arg) { /* perform action & invoke callback */ invoke_callback(); }
application:
main() { init_lib(); .... create_new_thread(); .... function1(10, 20); .... function2('c', 'd'); } another_thread() { function2('a', 'b'); .... }
the exact problem i'm not able solve what(how) locking mechanism need put in place block calls functions defined in library & wait callback 3rd party library provided library shall used in multi-process & multi-threaded environment.
using plain pthreads interface, use condition variables:
int lib_init() { pthread_cond_init(&cond, null); pthread_mutex_init(&mutex, null); register_callback(callback); } int lib_deinit() { unregister_callback(); pthread_mutex_destroy(&mutex); pthread_cond_destroy(&cond); } int callback(void *p) { pthread_mutex_lock(&mutex); result[??] = p; pthread_cond_broadcast(&cond); pthread_mutex_unlock(&mutex); } int function1(int, int) { result[??] = null; perform_action(); pthread_mutex_lock(&mutex); while (result[??] == null) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); } int function2(char, char) { result[??] = null; perform_action(); pthread_mutex_lock(&mutex); while (result[??] == null) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex); }
pthread_cond_wait()
unlocks mutex while waits.
the result[??]
stand-in method, you'll have come with, link particular callback invocation specific function1()
or function2()
call(s) relevant to.
Comments
Post a Comment