c - 在工作线程 epolled 和配置线程之间交换全局变量

标签 c linux pthreads mutex epoll

我有一个工作线程在 fds 和计时器上执行 epoll_wait,配置存储在全局上下文结构 (fdToRead) 中。 一些其他线程改变了这个全局结构。

这是原理图

工作线程

struct epoll_event ev
while(1){
    epoll_wait(&ev)
    // call to changeFd(path) done here from other thread
    get_mutex
    read(ev.data.fd)//this fd was just closed or re-affect to another file !!!
    ...
    put_mutex
}

来自任何线程的函数调用

changeFd(path){
  get_mutex
  close(fdToRead)
  fdToRead=openSocket(path)
  epoll_add(fdToRead)
  put_mutex
}

问题是,如果 changeFd 在 epoll_wait 之后和 get_mutex 之前被调用,我会在 fd 上收到事件,该事件已关闭或重新影响另一个“内核中的打开文件描述符”。

我可以用哪种方式做到这一点? 哪个模板模式?

是否可以做类似“epoll_wait 中的 get_mutex”之类的事情? 或者,“我可以在 epoll_wait 调用中阻止”工作线程吗?

最佳答案

您可以使用 accept()函数,它允许您接受套接字上的新连接,您的代码可能如下所示:

mutex_lock(...)
epoll_wait(...);
accept(...);
mutex_unlock(...);

关于c - 在工作线程 epolled 和配置线程之间交换全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33830336/

相关文章:

python - printf 如何损坏字符串?

c - SIGSEGV问题

linux - 无法执行 'x86_64-conda_cos6-linux-gnu-gcc' : No such file or directory (pysam installation)

从 pthread 内部调用函数?

c - C 中数组初始化中的方括号是什么意思?

c++ - C/C++ PCM开源音频分析仪

linux - 在 initrd 镜像中重新启动

linux - 从 Java/C++ 打印到终端的进度条

c++ - 编译时 -pthread 标志的意义

c - 在保留 CAP_SYS_NICE 的同时删除根 UID