首页 > 解决方案 > libevent 中的多线程

问题描述

我在 C 静态库中有一个线程(线程 A),它event_base在执行此操作后创建了 libevent:

#ifdef WIN32
    evthread_use_windows_threads();
#else
    evthread_use_pthreads();
#endif

这个 C 静态库都是单线程的,它自己完成所有的 libevent 工作:添加事件、调度、主循环等,所有这些都是从线程 A 完成的。

现在我有一个与上面的库链接的 C++ 程序,从一个boost::thread被调用的线程 B 调用C 库的入口函数。

在我的 C++ 程序的某个时刻,我还有另一个boost::thread名为 Thread C 的程序会尝试将event_addC 库用于 Thread A 的事件循环,然后立即调用event_active.

从 Thread C 做完事情后,我想看到的是:

calling event_add from Thread C
calling event_active from Thread C
Processing events from Thread A
calling the event's handler from Thread A

可能我们可以Processing events from Thread A在这些线之间有其他任何地方,但可以肯定的是,我们必须在 and 之间至少有 1 条这样的线event_activeevent handler execution对吧?

我看到的是:

calling event_add from Thread X
calling event_active from Thread X
calling the event's handler from Thread A

Thread X 与 Thread C 的 ID 不同,但我想这只是因为在 C++ 调用站点中使用了 boost 线程,在 C 库中使用了 pthreads 或其他东西,无论如何它不会打扰我。

我也喜欢这样一个事实,即我的主要目的是好的:从一个线程触发事件并从另一个线程处理它。

但是出于我自己的好奇心,我不明白为什么在调用处理程序回调之前我没有看到“处理来自线程 A 的事件”行?

线程 id 是用 获得的pthread_self(),这是在 Linux 上测试的,更具体地说是 Ubuntu 18.04。

标签: c++cmultithreadinglibevent

解决方案


推荐阅读