あなたの解決策は、1つの点を除いて合理的に聞こえます。各マシンに接続するスレッドを作成し、次に送信、受信、および解析を管理するサブスレッドを作成すると述べています。サブスレッドを作成する必要がある理由がわかりません。接続スレッドですべてを処理できるはずです。また、接続ごとに 1 つのスレッドではうまくスケーリングできない可能性があることも考慮してください。このアプリケーションが多数のマシンを処理する必要がある場合は、マシンごとにスレッドを使用することは避ける必要があります。
接続ごとに 1 つのスレッドを使用する代わりに、単純なスレッド プールを使用してこれを実現することもできますが、これではうまくスケーリングできません。5 秒ごとにワーカー キューに置かれるタスクを作成することを検討できます。スレッドのプールは、接続、読み取り、切断、解析、および処理を行います。これが TCP/IP であると仮定すると、HTTP と同様に、接続を開いたままにするのではなく、読み取りごとに接続/切断する必要があります。
これは、 vc ++ スレッド プール関連の質問です。そして、ここにいくつかの関連情報があります。
別の方法として、ソケット通信にlibeventを使用することもできます。解析に関しては、 Apache ThriftやJSonなど、使用できる他のライブラリもあり、これらはすべてオープン ソースです。これらの解析ライブラリの欠点は、オプションではない透析マシンも変更する必要がある場合があることです。Thrift のようなものを使用できる場合は、1 つのライブラリからすべてを取得できます: ソケット通信と解析。
接続ごとに 1 つのスレッドの単純なケースのコードを次に示します。
class ThreadInfo
{
public:
ThreadInfo(const string &ipAddress, uint16_t port) : ipAddress_(ipAddress), port_(port) {}
string getIpAddress() {return ipAddress_;}
uint16_t getPort() {return port_;}
string getRecvBuffer() {return recvBuffer_;}
private:
string ipAddress_;
uint16_t port_;
string recvBuffer_;
};
void *threadEntryPoint(void *userData)
{
ThreadInfo *threadInfo = (ThreadInfo*) userData;
// You need to decide if you want to keep the connection open while sleeping
// or open and close it for each transaction. Change code here accordingly.
// Create socket with threadInfo->getIpAddress() and threadInfo->getPort()
// while(1)
// Send request to each machine
// Get response from each machine and store in threadInfo->getRecvBuffer()
// The buffer could also be a local var in this function, decide accordingly
// parse data accordingly
// sleep 5 seconds
}
uint16_t getPort(int machineNum) { return 3456; }
string getIpAddress(int machineNum) { return string("192.168.1.2"); }
int main(int argc, char **argv)
{
// 3 items that we need, and that you will have to plugin accordingly:
// 1) Num threads, assuming 100 for now
// 2) IP address of each external machine, implement getIpAddress() accordingly
// 3) port of each machine, implement getPort() accordingly
int numThreads(100);
list<pthread_t> threadIdList;
for(int i = 0; i < numThreads; ++i)
{
pthread_t threadId;
ThreadInfo *threadInfo = new ThreadInfo(getIpAddress(i), getPort(i));
pthread_create(&threadId, NULL, threadEntryPoint, threadInfo);
threadIdList.push_back(threadId);
}
// Wait for the threads to finish
std::list<pthread_t>::iterator iter = threadIdList.begin();
while(iter != threadIdList.end())
{
pthread_t threadId = *iter++;
pthread_join(threadId, NULL);
}
}