gpt4 book ai didi

c - 如何在 C 中一起使用 libevent 和 pthread

转载 作者:太空狗 更新时间:2023-10-29 17:03:42 25 4
gpt4 key购买 nike

main函数是基于libevent的,但是函数中有一个long run task。于是启动N个treads来运行任务。这个想法可以吗?以及如何在 C 中同时使用 libevent 和 pthread?

最佳答案

碰到一个老问题,可能已经解决了。但发布答案以防万一其他人需要它。

是的,这种情况下做线程是可以的。我最近在 pthreads 中使用了 libevent,它似乎工作得很好。这是代码:

#include <stdint.h>
#include <pthread.h>
#include <event.h>

void * thread_func (void *);

int main(void)
{
int32_t tid = 0, ret = -1;
struct event_base *evbase;
struct event *timer;
int32_t *t_ret = &ret;
struct timeval tv;

// 1. initialize libevent for pthreads
evthread_use_pthreads();

ret = pthread_create(&tid, NULL, thread_func, NULL);
// check ret for error

// 2. allocate event base
evbase = event_base_new();
// 3. allocate event object
timer = event_new(evbase, -1, EV_PERSIST, callback_func, NULL);
// 4. add event
tv.tv_sec = 0;
tv.tv_usec = 1000;
evtimer_add(timer, &tv);
// 5. start the event loop
event_base_dispatch(evbase); // event loop

// join pthread...

// 6. free resources
event_free(timer);
event_base_free(evbase);
return 0;
}

void * thread_func(void *arg)
{
struct event *ev;
struct event_base *base;

base = event_base_new();
ev = event_new(base, -1, EV_PERSIST, thread_callback, NULL);
event_add(ev, NULL); // wait forever
event_base_dispatch(base); // start event loop

event_free(ev);
event_base_free(base);
pthread_exit(0);
}

如您所见,在我的例子中,主线程的事件是计时器。遵循的基本逻辑如下:

  1. 调用 evthread_use_pthreads() 为 Linux 上的 pthreads 初始化 libevent(我的案例)。对于 Windows evthread_use_window_threads()。查看 event.h 本身提供的文档。
  2. 按照文档中的说明在全局堆上分配一个event_base 结构。确保检查返回值是否有错误。
  3. 同上,但分配事件结构本身。在我的例子中,我没有等待任何文件描述符,所以 -1 作为参数传递。此外,我希望我的事件持续存在,因此 EV_PERSIST 。省略了回调函数的代码。
  4. 安排执行事件
  5. 启动事件循环
  6. 完成后释放资源。

在我的案例中使用的 Libevent 版本是 libevent2 5.1.9 ,您还需要 libevent_pthreads.so 库进行链接。

干杯。

关于c - 如何在 C 中一起使用 libevent 和 pthread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11117977/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com