如果在另一个线程中调用bufferevent_write,则bufferevent_write不会在伙伴上触发EV_READ,这很奇怪。
我准备了一个简化的程序来重现奇怪的结果。 超时回调中的bufferevent_write 立即触发伙伴上的EV_READ。但是在另一个线程中运行的bufferevent_write不会立即触发伙伴上的EV_READ。而是在超时事件之前调用do_read。
有人可以帮助解决问题。 非常感谢。
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include <event2/bufferevent.h>
#include <event2/event.h>
#define BUF_BODY "hello world\n"
void thr_fn( void * pArg )
{
struct bufferevent *pBufEv = (struct bufferevent *)pArg;
while (1)
{
// write doesn't trigger EV_READ event on the partner.
bufferevent_write(pBufEv, BUF_BODY, strlen(BUF_BODY) + 1);
printf("write\n");
sleep(5);
}
}
void do_read( struct bufferevent * pBEv, void * pArg )
{
char buff[1024];
bufferevent_read(pBEv, buff, 1024);
puts(buff);
return;
}
static void
ev_timeout_cb (evutil_socket_t sock_fd, short events, void *ctx)
{
struct bufferevent * pBufEv = (struct bufferevent * )ctx;
puts("ev_timeout_cb ...\n");
// write immediately trigger EV_READ event on the partner.
//bufferevent_write(pBufEv, BUF_BODY, strlen(BUF_BODY) + 1);
}
int main( void )
{
struct event_base * pEventBase = NULL;
struct bufferevent * aPair[2] = {NULL};
// evthread_use_pthreads();
pEventBase = event_base_new();
int nRet = bufferevent_pair_new(pEventBase, 0, aPair);
bufferevent_setcb(aPair[0], do_read, NULL, NULL, NULL);
bufferevent_enable(aPair[0], EV_READ);
pthread_t tid;
pthread_create(&tid, NULL, thr_fn, aPair[1]);
struct timeval tv = {10, 0};
evtimer_add(event_new(pEventBase, -1, EV_PERSIST, ev_timeout_cb, aPair[1]), &tv);
event_base_dispatch(pEventBase);
return 0;
}