Next, take thrift as an example.
As a server, it should be able to receive data from multiple clients at the same time, so the server should implement a multi-threaded mechanism.
Follow these three steps to rewrite the server (serv_server.skeleton.cpp) to implement multithreading.
(1) The code for using the main function of the thread pool is as follows:
Int main (INT argc, char ** argv ){
// Thread Pool
Shared_ptr <servhandler> handler (New servhandler ());
Shared_ptr <tprocessor> processor (New servprocessor (handler ));
Shared_ptr <tprotocolfactory> protocolfactory (New tbinaryprotocolfactory ());
Shared_ptr <ttransportfactory> transportfactory (New tbufferedtransportfactory ());
Shared_ptr <tservertransport> servertransport (New tserversocket (9090 ));
// Specify 15 threads
Shared_ptr <threadmanager> threadmanager = threadmanager: newsimplethreadmanager (15 );
Shared_ptr <posixthreadfactory> threadfactory
= Shared_ptr <posixthreadfactory> (New posixthreadfactory ());
Threadmanager-> threadfactory (threadfactory );
Threadmanager-> Start ();
Printf ("start.../N ");
Tthreadpoolserver server (processor,
Servertransport,
Transportfactory,
Protocolfactory,
Threadmanager );
Server. Serve ();
Printf ("End/N ");
Return 0;
}
Pay attention to the red keywords in the Code and change them to the names defined in your own service.
(2) header file:
# Include <concurrency/threadmanager. h>
# Include <concurrency/posixthreadfactory. h>
# Include <server/tthreadpoolserver. h>
# Include <server/tthreadedserver. h>
Add all the values that can be added to avoid the following errors:
Error: 'threadmanager' was not declared in this scope
(3) namespace: Using namespace: Apache: thrift: concurrency;
Otherwise, an error occurs: Error: 'posixthreadfactory 'was not declared in this scope
Concurrency corresponds to the file directory in # include
When each client is connected, the server starts a thread to serve it. After data transmission is completed, the server recycles this thread.