1 // excerpts from http://code.google.com/p/muduo/
2 //
3 // Use of this source code is governed by a BSD-style license
4 // that can be found in the License file.
5 //
6 // Author: Shuo Chen (chenshuo at chenshuo dot com)
7 
8 #ifndef MUDUO_NET_TCPSERVER_H
9 #define MUDUO_NET_TCPSERVER_H
10 
11 #include "Callbacks.h"
12 #include "TcpConnection.h"
13 
14 #include <map>
15 #include <boost/noncopyable.hpp>
16 #include <boost/scoped_ptr.hpp>
17 
18 namespace muduo
19 {
20 
21 class Acceptor;
22 class EventLoop;
23+class EventLoopThreadPool;
24 
25 class TcpServer : boost::noncopyable
26 {
27  public:
28 
29   TcpServer(EventLoop* loop, const InetAddress& listenAddr);
30   ~TcpServer();  // force out-line dtor, for scoped_ptr members.
31 
32+  /// Set the number of threads for handling input.
33+  ///
34+  /// Always accepts new connection in loop's thread.
35+  /// Must be called before @c start
36+  /// @param numThreads
37+  /// - 0 means all I/O in loop's thread, no thread will created.
38+  ///   this is the default value.
39+  /// - 1 means all I/O in another thread.
40+  /// - N means a thread pool with N threads, new connections
41+  ///   are assigned on a round-robin basis.
42+  void setThreadNum(int numThreads);
43+
44   /// Starts the server if it's not listenning.
45   ///
46   /// It's harmless to call it multiple times.
47   /// Thread safe.
48   void start();
49 
50   /// Set connection callback.
51   /// Not thread safe.
52   void setConnectionCallback(const ConnectionCallback& cb)
53   { connectionCallback_ = cb; }
54 
55   /// Set message callback.
56   /// Not thread safe.
57   void setMessageCallback(const MessageCallback& cb)
58   { messageCallback_ = cb; }
59 
60   /// Set write complete callback.
61   /// Not thread safe.
62   void setWriteCompleteCallback(const WriteCompleteCallback& cb)
63   { writeCompleteCallback_ = cb; }
64 
65  private:
66   /// Not thread safe, but in loop
67   void newConnection(int sockfd, const InetAddress& peerAddr);
68+  /// Thread safe.
69   void removeConnection(const TcpConnectionPtr& conn);
70+  /// Not thread safe, but in loop
71+  void removeConnectionInLoop(const TcpConnectionPtr& conn);
72 
73   typedef std::map<std::string, TcpConnectionPtr> ConnectionMap;
74 
75   EventLoop* loop_;  // the acceptor loop
76   const std::string name_;
77   boost::scoped_ptr<Acceptor> acceptor_; // avoid revealing Acceptor
78+  boost::scoped_ptr<EventLoopThreadPool> threadPool_;
79   ConnectionCallback connectionCallback_;
80   MessageCallback messageCallback_;
81   WriteCompleteCallback writeCompleteCallback_;
82   bool started_;
83   int nextConnId_;  // always in loop thread
84   ConnectionMap connections_;
85 };
86 
87 }
88 
89 #endif  // MUDUO_NET_TCPSERVER_H
90