我想通过 eventfd 在线程之间传输数据。所以我写了以下代码来满足我的需要。我的主机操作系统是 openSUSE v12.3 64bit。
#include "stdio.h"
#include "unistd.h"
#include "pthread.h"
#include "sys/eventfd.h"
#include "sys/epoll.h"
#define nil NULL
int efd = -1;
void* read_thread(void* arg) {
int ret = 0;
uint64_t count = 0;
int ep_fd = -1;
struct epoll_event events[10];
(void)(arg);
if (efd < 0) {
printf("efd not inited.\n");
return nil;
}
ep_fd = epoll_create(1024);
if (ep_fd < 0) {
perror("epoll_create fail: ");
return nil;
}
{
struct epoll_event read_event;
read_event.events = EPOLLIN;
read_event.data.fd = efd;
ret = epoll_ctl(ep_fd, EPOLL_CTL_ADD, efd, &read_event);
if (ret < 0) {
perror("epoll ctl failed:");
return nil;
}
}
while (1) {
ret = epoll_wait(ep_fd, events, 10, 5000);
if (ret > 0) {
int i = 0;
for (i = 0; i < ret; i++) {
if (events[i].events & (EPOLLHUP | EPOLLERR)) {
printf("epoll eventfd has epoll hup.\n");
break;
} else if (events[i].events & EPOLLIN) {
int event_fd = events[i].data.fd;
ret = eventfd_read(event_fd, &count);
if (ret < 0) {
perror("read fail:");
break;
} else {
printf("read %llu\n", count);
}
}
}
} else if (ret == 0) {
break;
} else {
perror("epoll wait error:");
break;
}
}
close(ep_fd);
return nil;
}
int main(int argc, char *argv[]) {
pthread_t pid = 0;
uint64_t count = 0;
int ret = 0;
int i = 0;
efd = eventfd(0, EFD_NONBLOCK | EFD_CLOEXEC);
if (efd < 0) {
perror("eventfd failed.");
return -1;
}
ret = pthread_create(&pid, NULL, read_thread, NULL);
if (ret < 0) {
perror("pthread create:");
close(efd);
return -2;
}
for (i = 0; i < 5; i++) {
count = i + 1;
ret = eventfd_write(efd, count);
if (ret < 0) {
perror("write event fd fail:");
break;
} else {
printf("write %llu\n", count);
}
}
sleep(3);
pthread_join(pid, NULL);
close(efd);
efd = -1;
return 0;
}
我认为 eventfd 的行为应该像一个管道。所以程序的输出结果可能如下:
写1 读1 写2 读2 写3 读3 写4 读4 写5 读5
然而,它的实际结果是:
写 1 写 2 写 3 写 4 写 5 读 15
或者
写 1 写 2 写 3 写 4 写 5 读 1 读 14
有好心人能告诉我为什么输出结果是输入结果的总和吗?
我无法通过线程之间的 eventfd 正确传输数据。我也不喜欢管子。如何在线程之间正确地一一传输数据?