实现了多线程UDP服务器问题(线程池?) [英] Problems implementing a multi-threaded UDP server (threadpool?)

查看:699
本文介绍了实现了多线程UDP服务器问题(线程池?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个音频流光(客户端 - 服务器)作为我的一个项目(C / C ++)
我决定做一个多线程UDP服务器为这个项目。

I am writing an audio streamer (client-server) as a project of mine (C/C++), and I decided to make a multi threaded UDP server for this project.

这背后的逻辑是,每个客户端将在其自己的线程来处理。
具有我真的问题是线程彼此干扰

The logic behind this is that each client will be handled in his own thread. The problems I`m having are the interference of threads to one another.

我的服务器做的第一件事情是创造一种线程池;它创建5
所有由 recvfrom的()功能自动阻塞的线程,
虽然看似是,在大多数时候,当我连接其他设备
到服务器,一个以上的线程响应并稍后
这导致服务器完全阻塞,而不是进一步的操作。

The first thing my server does is create a sort of a thread-pool; it creates 5 threads that all are blocked automatically by a recvfrom() function, though it seems that, on most of the times when I connect another device to the server, more than one thread is responding and later on that causes the server to be blocked entirely and not operate further.

这是pretty很难调试这也让我为了写在这里
要获得关于如何平时多线程的UDP服务器实​​现的一些建议。

It's pretty difficult to debug this as well so I write here in order to get some advice on how usually multi-threaded UDP servers are implemented.

我应该使用互斥或​​信号在code的一部分?如果是这样,在哪里?

Should I use a mutex or semaphore in part of the code? If so, where?

任何想法将极有帮助。

推荐答案

我的服务器做的第一件事情是创造一种线程池;它创建5个线程,所有由recvfrom的()函数自动阻止,但它似乎是,在大多数时候,当我另一台设备连接到服务器,多个线程正在响应,后来导致该服务器成为完全堵塞不能再操作

而不是让所有的线程坐在一个recvfrom的()同一个套接字连接,您应该保护与信号的连接,让您的工作线程等待信号量。当一个线程获取信号量,它可以调用recvfrom的(),并且当与一个分组返回时,线程可以释放信号量(另一个线程获得),并处理该数据包本身。当它完成服务包,它可以返回到等待的信号。这样一来,您就不必线程之间传输数据。

Rather than having all your threads sit on a recvfrom() on the same socket connection, you should protect the connection with a semaphore, and have your worker threads wait on the semaphore. When a thread acquires the semaphore, it can call recvfrom(), and when that returns with a packet, the thread can release the semaphore (for another thread to acquire) and handle the packet itself. When it's done servicing the packet, it can return to waiting on the semaphore. This way you avoid having to transfer data between threads.

这篇关于实现了多线程UDP服务器问题(线程池?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆