简体   繁体   English

非阻塞写入和阻塞接收

[英]Non Blocking write, and blocking recv

I am trying to write a parallel stream for my C proxy, where data is simultaneously written to a parallel log while forwarding it to the destination server. 我正在尝试为我的C代理编写并行流,其中将数据同时写入并行日志,同时将其转发到目标服务器。 Essentially I am looking to have 2 threads where: 本质上,我正在寻找2个线程,其中:

  1. Thread does a non blocking write to a buffer 线程对缓冲区执行非阻塞写入
  2. 2nd Thread does a blocking read from the buffer. 第二线程执行从缓冲区的阻塞读取。

Naturally, the writer thread can exceed the reader thread. 自然,写程序线程可以超过读程序线程。 Hence whenever, a buffer overflow does happen, we raise and flag it as an error. 因此,每当确实发生缓冲区溢出时,我们都会将其引发并标记为错误。

Let's say that Thread 1(the writer), is 5 times as fast as Thread 2( the reader). 假设线程1(编写者)的速度是线程2(读者)的5倍。 I want Thread 1 not to slowdown, and write at 5x the speed of the reader (ie the buffer should not be locked away by the reader etc.). 我希望线程1不会减慢速度,并以读取器速度的5倍进行写入(即缓冲区不应被读取器等锁住)。 This will obviously lead to a buffer overflow since thread 1 is writing much faster than thread 2 is reading( I want to capture buffer overflow as well) 这显然会导致缓冲区溢出,因为线程1的写入速度快于线程2的读取速度(我也想捕获缓冲区溢出)

My understanding is sockets/file descriptors are either blocking or non blocking, cannot have write operations as non blocking and read as blocking. 我的理解是套接字/文件描述符要么是阻塞的,要么是非阻塞的,不能将写操作作为非阻塞,而不能将读取作为阻塞。 I am guessing this is to avoid buffer overflows. 我猜这是为了避免缓冲区溢出。 However, I am fine with buffer overflows. 但是,缓冲区溢出我很好。

Can anyone help in devising how such parallel threads can be created where the producer is non blocking, and the receiver is blocking? 任何人都可以帮助设计如何在生产者非阻塞而接收者阻塞的情况下创建此类并行线程吗?

You can use select() to block until the socket is readable. 您可以使用select()进行阻塞,直到套接字可读为止。 Leave it in non-blocking mode. 使其处于非阻塞模式。 If send() returns -1 and errno is set to EAGAIN or EWOULDBLOCK then you will need to use select() to tell you when the socket has become writable again. 如果send()返回-1errno设置为EAGAINEWOULDBLOCK则您将需要使用select()来告诉您套接字何时再次变为可写状态 Only do that when send() reports EAGAIN / EWOULDBLOCK , as sockets are almost always writable. 仅当send()报告EAGAIN / EWOULDBLOCK时才这样做,因为套接字几乎总是可写的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM