在 C 中发送帧的套接字和线程方法(win32)

发布于 2024-10-16 04:04:17 字数 473 浏览 10 评论 0原文

我正在创建一个简单的程序来从 USB 设备 (USBCap) 捕获帧,然后通过网络将其发送到我的第二个程序图像服务器 (IMGSvr)。

这两个程序将永远在同一台计算机或同一本地网络中运行。

USBCap 捕获超过 1 个 USB 设备(称为“通道”)。为此,我对每个通道使用线程过程,该过程从 DirectShow 包装器 (videoInput) 获取新帧。

问题始于套接字:它仅使用一个 TCP SOCK_STREAM 连接将帧发送到 IMGSvr。 send() 正在阻止发送 (由其他线程) util 帧的后续调用。

那么,如果它阻止所有线程,为什么我要使用多线程程序呢?

解决这个问题的最好方法是什么?也许使程序适应线程,将新帧放入帧队列中,以便另一个线程清空该队列,将排队的帧发送到 IMGSvr。

你怎么认为?

当写入新元素时,我需要在该队列中实现 LOCK 吗?

谢谢, 丹尼尔·科赫

I'm creating a simple program to capture frames from USB devices (USBCap) to send it through network to my second program, the Image Server (IMGSvr).

Both programs will run in the same machine or in the same local network, ever.

The USBCap captures more than 1 USB device (named "channel"). To do this, I'm using a threaded procedure to each channel, which is getting new frames from DirectShow wrapper (videoInput).

The problem starts in the socket: It's using just one TCP SOCK_STREAM connection to send frames to IMGSvr. send() is blocking subsequent calls of send() (by other threads) util frame is sent.

So if it blocks all threads, why I'm using multi threaded program?

What's the best way to solve it? Maybe adapt the program to threads puts new frames in a frame's queue so another thread to empty this queue, sending queued frames to the IMGSvr.

What do you think?

Need I implement a LOCK in this queue, when writing a new element?

Thanks,
Daniel Koch

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唐婉 2024-10-23 04:04:17

send() 保证写入是原子的,尽管它不能保证传递给单个调用的所有数据都会被接受。因此,第二个线程必须等待,直到第一个线程将其数据附加到发送队列。

这样做几乎从来都不是一个好主意,因为在某些情况下,数据将仅被部分接受,之后套接字被解锁并且第二个线程获得机会 - 在这种情况下,您将最终得到无效的输出流。

使用专门的编写器和排队机制的方法似乎是正确的。您将需要一个锁来保护队列,但是将项目附加到链接列表所需的关键部分非常短,因此这里不应该有任何争用。

send() guarantees that writes are atomic, even though it does not guarantee that all the data passed to a single invocation will be accepted. Thus, the second thread has to wait until the first thread has appended its data to the send queue.

It is almost never a good idea to do this, as there are cases where data will be accepted only partially, after which the socket is unlocked and the second thread gets its chance -- in this case you will end up with an invalid output stream.

The approach with a dedicated writer and a queueing mechanism appears to be correct. You will need a lock to protect the queue, but the critical section required to append an item to a linked list is very short, so there shouldn't be any contention here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文