用于在 C++ 中读取和写入 SERVER 的多线程

Multi threading for reading and writing to SERVER in c++

我有一个要求,我必须在套接字上写入,然后从套接字中连续读取响应并处理数据。 我创建了 2 类 A 和 B。A 有 write() 和 read() api,B 有 processdata() api。 我已经创建了从 A::read() 到 B::processdata() 的回调。 但我面临多线程问题,因为我是新手。 read() api 的线程必须始终为 运行,但是在 B::processdata() 中处理数据时,服务器正在 socket read() 上发送更多数据,这是我丢失的。 请针对此问题提出一些设计建议,以便我可以继续存储数据,而我的 processdata 函数可能会完成其工作并可以再次返回以读取数据(以小示例为例)? 我正在考虑维护 3 个线程,每个 write , read 和 processdata 1个。但是我不确定如何在完成 processdata 线程后返回读取线程。

抱歉这么久 post 但如果有人能帮助我,我将不胜感激。

下面是我在项目中的高级代码设计。

 //A.cpp
        class A {
        public:
          void  write();
           void read(b* obj);
        }
        void A::write()
        { 
           //code to write to socket  

          }
        void A::read(b* obj)
        { 
           //code to read from socket  
          // if data received call below function 
          obj->processdata(buffer)
          }

    //B.cpp    
        class B {
        public:
            processdata(buffer)
        }

        void B::processdata(buffer)
        { 
           //code to processdaata from socket  
          }
//Main.cpp
        int main()
        {
          A* objA = new A;
          B* objB = new B;
          objA->write()
          while(1)
           {
             objA->read(objB)
            }
        }

A.cpp

extern  CRITICAL_SECTION    g_cCritSec;
        class A {
        public:
          static void  write();
          static void read(void* obj);
        }
        void A::write()
        { 

           EnterCriticalSection(&g_cCritSec);
           //code to write to socket 
           LeaveCriticalSection(&g_cCritSec); 

        }
        void A::read(void* obj)
        { 
           EnterCriticalSection(&g_cCritSec);
           while(1)
           {
              //code to read from socket  
              // if data received call below function 
              // send separate copy of buffer to avoid overrite
              uintptr_t Thread2 = _beginthread( B::processdata, 0, (void *) buffer); 

              //obj->processdata(buffer)
           }
           LeaveCriticalSection(&g_cCritSec);
        }

B.cpp

  extern    CRITICAL_SECTION    g_cCritSec;
        class B {
        public:
            static processdata( void *buffer)
        }

        void B::processdata(void *buffer)
        {  
           Buffer *bufferReceive = (Buffer*)buffer;
           //code to processdaata from socket   
        }

Main.cpp

CRITICAL_SECTION    g_cCritSec;
        int main()
        {

          InitializeCriticalSection(&g_cCritSec); 
          B* objB = new B;
          objA->write();
          uintptr_t Thread1 = _beginthread( A::read, 0, (void *) objB); 

          DeleteCriticalSection(&g_cCritSec); 
        }

这个回答对您有帮助吗?一个最小的多线程应用程序,将启动 Thread1 作为静态成员函数 A::Read 作为例程(我们需要将成员函数定义为静态以用作线程回调)。从 Read 函数,它将启动另一个线程,并向其传递 buffer 的副本。这里两个线程将同时执行