【发布时间】:2015-06-25 08:34:25
【问题描述】:
我需要创建一个共享库来公开一组 API,这些 API 将被多个进程使用,这些进程可能有多个线程从其中调用 API。
这个共享库又使用另一个我需要注册回调的第 3 方共享库。第 3 方库从不同的线程调用注册的回调。
我想知道如何在调用我的库中定义的 API 时阻止线程,并在我从 3rd 方库获得回调时释放它。此锁定不应阻止其他线程调用相同的 API...!
我正在使用 pthread 库来创建我的库。
伪代码:
我的图书馆:
int lib_init()
{
register_callback(callback);
}
int lib_deinit()
{
unregister_callback();
}
int callback(void *)
{
<unblock the functions>
}
int function1(int, int)
{
perform_action();
<should block till I get a callback from 3rd party library>
}
int function2(char, char)
{
perform_action();
<should block till I get a callback from 3rd party library>
}
第三方库:
int register_callback(callback)
{
....
launch_thread();
....
}
int unregister_callback()
{
....
terminate_thread();
....
}
int perform_action()
{
/* queue action */
}
void* thread(void*arg)
{
/* perform the action & invoke callback */
invoke_callback();
}
应用:
main()
{
init_lib();
....
create_new_thread();
....
function1(10, 20);
....
function2('c', 'd');
}
another_thread()
{
function2('a', 'b');
....
}
我无法解决的确切问题是我需要设置什么(如何)锁定机制来阻止对我的库中定义的函数的调用并等待来自 3rd 方库的回调,前提是我的库应该被使用在多进程和多线程环境中。
【问题讨论】:
标签: c++ linux multithreading pthreads shared-libraries