将信息传递给多个线程

时间:2011-03-10 13:13:05

标签: c++ multithreading

我正在研究MultiThreaded TCP Server(c ++),它将为多个客户端提供流式传输视频。 我决定采用“每个客户端的线程”方法。并发客户不超过100个。

我使用select系统调用多路复用客户端并接受(接受),然后创建线程以流式传输视频。

  1. 在这种情况下,这是正确的方法吗?
  2. 我需要传递某些信息,例如(socket id和handle to thread,threadID等,以及其他信息来传输视频)。我如何将这些信息传递给所有线程,因为这些信息并非所有线程都通用。我不想为线程和线程id获取HANDLE数组。

3 个答案:

答案 0 :(得分:4)

请不要“重新发明轮子”。

例如,boost :: asio库在创建如您所描述的服务器方面提供了巨大的帮助。有很多教程和示例 - 对您来说最直接有用的可能是http://www.boost.org/doc/libs/1_46_0/doc/html/boost_asio/example/echo/async_tcp_echo_server.cpp

答案 1 :(得分:0)

通常开始一个帖子,
ether使用void函数或函子类的标准方法:

class StreamInfo
{
   public:
      int _id;
      std::string _ip;
      int _port;
      int status;
      StreamInfo(int id, string ip, int p):_id(id), _ip(ip), _port(p){};
};

void myThread(void* datastruct)
{
      StreamInfo* info = static_cast<StreamInfo*>(datastruct);
      ..
      ..
      //busy wait..
      while(...)
      {
          // check for some new info
          if(info->status)....
       }
}

main(..)
{
    multimap<int, StreamInfo*> mmap;
    SOCK s=null;
    StramInfo* i=null;
    while(s = accept(sock))
    {
       i=new StreamInfo(12, "localhost", 5000);
       id = createThread(...myThread, i);
       ....
       mmap.append(pair<..,..>(id, i);
    };

};

//...some other thread
/// change StreamInfo status for thread 12
mmap.last(12).status = 134;
//... then thread 12 will automatically recon this change in busy wait.

它只是一种方法,你也可以使用观察者模式。 但这需要更多的工作。

我认为流媒体的带宽,CPU和内存消耗很大 因此,在线程之间切换可能效率不高 也许看看异步方法。

Boost :: ASIO非常适合这个目的,适用于所有平台。

答案 2 :(得分:0)

“每个客户端的线程”不是可扩展的方法,特别是对于视频流服务器(通常需要高性能)。查看Boost.Asio库,尤其是示例"An HTTP server using a single io_service and a thread pool calling io_service::run()."(只是忽略特定于HTTP的内容)。使用Boost.Asio,您将获得高性能的可扩展多线程服务器,而不会头疼。

相关问题