116-poll 函数

poll 完成的功能和 select 几乎是一模一样的,所以在你学会了 select 后,你发现学 poll 会非常容易。在英文中 poll 表示“投票”的意思,这非常形象,有事件发生的描述符,就为其投票。

1. poll 原型

int poll(struct pollfd *fds, nfds_t nfds, int timeout);

有几个参数类型可能我们不认识,实际上 poll 函数的第一个参数是一个类型为 struct pollfd 的数组,第二个参数 nfds (一般是个无符号的整型)是这个数组的大小,第三个参数就是超时时间了。接下来一个一个说明。

1.1 struct pollfd 类型

struct pollfd {
  int   fd;         /* 文件描述符 */
  short events;     /* 监听的事件,比如可读事件,可写事件 */
  short revents;    /* poll 函数的返回结果,是可读还是可写 */
};

和 select 不同的是,poll 函数没有将可读事件、可写事件描述符单独放进两个不同的集合,而是分配了一个结构体,一次性进行监听。

成员 fd 表示要监听哪个描述符,如果该值是负数,poll 函数会忽略掉它。

对 events 来说,它使用 bit 位来保存你要监听什么事件,通常用“位或”操作为其赋值,在 linux 中,events 有下面的可选值:

  • POLLIN: 监听是描述符是否可读,相当于 select 中的读集合参数。
  • POLLPRI:监听是否有紧急数据可读(比如 TCP 套接字上的 out-of-band(OOB) 数据,这种我们还没学,所以不考虑监听它了)
  • POLLOUT:监听是描述符是否可写。
  • POLLRDHUP:这种事件只有 Linux 2.6.17 内核后才支持,它监听流式套接字对端是否关闭右半关闭,因为我们还没学套接字,所以这种的也先不考虑了。

如果有监听的事件到来,它会将事件类型保存到 revents 成员中,比如监听到了有数据可读,则 revents 的 bit 位中会保存 POLLIN。如果监听到了有数据可写,那 revents 的 bit 位中会保存 POLLOUT。

还有一些事件,即使你不主动监听它也会发生,并保存到 revents 中,这些事件一般都是异常事件:

  • POLLERR:这种情况极少见,很抱歉后面的实验没演示。一般是硬件上的问题吧,可以参考这个帖子传送门
  • POLLHUP:对端挂断,比如对于有名管道,其中一端关闭了。
  • POLLNVAL:使用了未打开的描述符

1.2 timeout 参数

  • timeout = -1,表示永远等待,直到有事件发生。
  • timeout = 0,不等待,立即返回。
  • timeout > 0,等待 timeout 毫秒。

2. poll 与 select

这两个函数所做的事件是一样的,但是它们也有区别:

  • select 使用 fd_set 来存放描述符,poll 使用结构体数组。
  • select 能够一次监听的描述符数量是受 fd_set 集合的限制的,通常这个集合最多只能放 1024 个描述符。而 poll 一次能够监听的描述符个数是根据数组大小来决定的,这要看 nfds_t 被定义成什么类型了,如果是 unsigned long,4 字节宽度的情况下,poll 能监听 2321 2 32 − 1 个描述符。

3. 实验

程序 poll.c 只是对前面的 select.c 做了一点点修改,将 select 替换成了 poll 函数。另外,为了能演示异常事件,程序使用了一个未打开的描述符 fd3。

writepipe 函数做了一点点小小的修改,就是输入字母 ‘q’ 的时候会主动 close 掉管道描述符,同时退出。

poll 函数同样会被信号打断,所有

3.1 代码

// poll.c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <poll.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <signal.h>

#define PERR(msg) do { perror(msg); exit(1); } while(0);

void handler(int sig) {
  if (sig == SIGINT) {
    puts("hello SIGINT");
  }
}

int process(char* prompt, int fd) {
  int n;
  char buf[64];
  char line[64];
  n = read(fd, buf, 64);
  if (n < 0) {
    // error
    PERR("read");
  }
  else if (n == 0) {
    // peer close
    sprintf(line, "%s closed\n", prompt);
    puts(line);
    return 0;
  }
  else if (n > 0) {
    buf[n] = 0;
    sprintf(line, "%s say: %s", prompt, buf);
    puts(line);
  }
  return n;
}

int main () {
  int i, n, res;
  char buf[64];

  struct pollfd fds[4];

  if (SIG_ERR == signal(SIGINT, handler)) {
    PERR("signal");
  }

  int fd0 = STDIN_FILENO;
  int fd1 = open("a.fifo", O_RDONLY);
  printf("open pipe: fd = %d\n", fd1);
  int fd2 = open("b.fifo", O_RDONLY);
  printf("open pipe: fd = %d\n", fd2);
  int fd3 = 100;

  fds[0].fd = fd0;
  fds[1].fd = fd1;
  fds[2].fd = fd2;
  fds[3].fd = fd3;

  for (i = 0; i < 4; ++i) {
    fds[i].events = POLL_IN;
  }


  while(1) {
    res = poll(fds, 4, -1);

    if (res < 0) {
      // error
      if (errno == EINTR) {
        perror("poll");
        continue;
      }
      PERR("poll");
    }
    else if (res == 0) {
      // timeout
      continue;
    }

    for (i = 0; i < 4; ++i) {
      if (fds[i].revents & POLLIN) {
        sprintf(buf, "fd%d", i);
        n = process(buf, fds[i].fd);
        if (n == 0) fds[i].fd = -1;
      }
      if (fds[i].revents & POLLERR) {
        printf("fd%d Error\n", i);
        fds[i].fd = -1;
      }
      if (fds[i].revents & POLLHUP) {
        printf("fd%d Hang up\n", i);
        fds[i].fd = -1;
      if (fds[i].revents & POLLNVAL) {
        printf("fd%d Invalid request\n", i);
        fds[i].fd = -1;
      }
    }
  }
}

3.2 编译与运行

  • 编译
$ gcc poll.c -o poll
  • 运行


这里写图片描述
图1 运行结果

从图 1 中可以看到,因为传入了一个未打开的描述符,导致 poll 函数监听到了异常事件,即 POLLNVAL,所以屏幕打印了 fd3 Invalid request.

当 writepipe 通过正常方式(按下 q)或者直接使用 CTRL + C 退出时,poll.c 程序都能监听到异常事件 POLLHUP,因此在屏幕打印 fd1 Hang up 和 fd2 Hang up.

因为信号可以打断 poll 函数,所以当我们按下 CTRL + C 时,先执行信号处理函数,然后打印 poll: Interrupted system call.

4. 总结

  • 掌握 poll 的用法
  • 知道 poll 和 select 的区别
### Push-Pull Loss Function in Machine Learning The push-pull loss function serves as an effective approach within the realm of metric learning, aiming at enhancing discriminative power by simultaneously pushing apart samples from different classes while pulling together those from the same class[^1]. This dual mechanism ensures that feature embeddings generated through deep neural networks maintain both intra-class compactness and inter-class separability. In practical implementation, this involves two components: #### Pull Component For each sample \(i\) belonging to a specific class, pull component minimizes distances between itself and other members within the same category. Mathematically speaking, given anchor point \(a\), positive example \(p\): \[ L_{pull} = \sum_i ||f(a_i)-f(p_i)||_2^2 \] where \( f(\cdot) \) represents embedding space transformation learned via network parameters during training process. #### Push Component Conversely, push component maximizes separation among negative examples (samples not sharing common labels with anchors). For every pair consisting of one anchor and multiple negatives (\(n_j\)), \[ L_{push} = -\log{\left[\frac{e^{-||f(a_i)-f(n_j)||}} {\sum_k e^{-||f(a_i)-f(n_k)||}}}\right]} \] Combining these terms yields overall objective function used throughout optimization phase: \[ L_{total}=L_{pull}+\alpha * L_{push} \] Herein lies parameter \(\alpha\) controlling balance between attraction forces inside clusters versus repulsion outside them; fine-tuning such hyperparameters plays crucial role towards achieving optimal performance metrics across various datasets and tasks. ```python import torch from torch import nn class PushPullLoss(nn.Module): def __init__(self, alpha=0.5): super(PushPullLoss, self).__init__() self.alpha = alpha def forward(self, anchor_embeddings, positive_embeddings, negative_embeddings): # Calculate pull term pull_loss = ((anchor_embeddings - positive_embeddings)**2).mean() # Calculate push term using softmax margin-based formulation neg_distances = torch.norm(anchor_embeddings.unsqueeze(-1) - negative_embeddings.T, dim=-1) pos_distance = torch.norm(anchor_embeddings - positive_embeddings, dim=-1) exp_neg_dist = (-neg_distances).exp().sum(dim=-1) push_loss = -(pos_distance.exp() / exp_neg_dist).log().mean() total_loss = pull_loss + self.alpha * push_loss return total_loss ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值