summaryrefslogtreecommitdiff
path: root/docs/tutorials/005/page07.html
blob: 565e15a4691701047ab6c97fa642e1021bd077ba (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2//EN">
<HTML>
<HEAD>
   <TITLE>ACE Tutorial 005</TITLE>
   <META NAME="GENERATOR" CONTENT="Mozilla/3.0Gold (Win95; I) [Netscape]">
   <META NAME="Author" CONTENT="Billy Quinn">
   <META NAME="Description" CONTENT="A first step towards using ACE productively">
</HEAD>
<BODY text = "#000000" link="#000fff" vlink="#ff0f0f" bgcolor="#ffffff">


<CENTER><P><B><FONT SIZE=+2>ACE&nbsp;Tutorial 005<BR>
Creating a MultiThreaded Server </FONT></B></P></CENTER>

<P>
<HR WIDTH="100%"></P>

<UL>
<P>The solution provided previously proposes a solution to deal with multiple connections per
thread reactor, which is what we will build on in the next tutorial. In
conjunction with this , it is beneficial to examine an alternative solution
to this tutorial's specific purpose, which is to introduce the notion of
a reactor per thread which will represent a single client connection to the server.
As in the previous solution , the thread will exit immediately once the
connection is terminated, so multiple connections per reactor are not implemented. However, the previous solution
introduced a mechanism that would allow the reactor to handle multiple connections
, by using the derived reactor object with a counter. It is important to
note that the following solution does not provide this, but it addresses
the specific objective of a reactor per thread. It also introduces the
really cool notion of an active object using a function call (<TT>activate()</TT>)
to start itself running. This idea will also be built upon in future tutorials.</P>
</UL>

<UL>
<PRE>// $Id$

// ============================================================================ // 
// = FILENAME
//    Connection_Handler.cpp
//
// = DESCRIPTION
//      This test illustrates how to create multiple threads, each       
//
// = AUTHOR
//    Doug Schmidt
// 
// ============================================================================
             
             
1.      #include &quot;ace/Acceptor.h&quot;
2.      #include &quot;ace/SOCK_Acceptor.h&quot;
3.      #include &quot;ace/Service_Config.h&quot;
4.      #include &quot;ace/Thread.h&quot;
             
5.      class Connection_Handler : public ACE_Svc_Handler&lt;ACE_SOCK_STREAM, 
6.      ACE_NULL_SYNCH&gt;
        {
        public:
7.        virtual int open (void *);
          // Initialize the &lt;Connection_Handler&gt; and make it an Active Object.
             
8.        virtual int close (u_long);
          // Terminate the &lt;Connection_Handler&gt;.
             
9.        virtual int svc (void);
          // Run the &lt;Connection_Handler&gt;'s main event loop.
             
        protected:
10.       virtual int handle_close (ACE_HANDLE, 
11.                                 ACE_Reactor_Mask);
          // Signal the Active Object to stop when called.
             
12.       virtual int handle_input (ACE_HANDLE); 
          // Handle input from the client.
             
13.       virtual int handle_timeout (const ACE_Time_Value &amp;tv, 
14.                                   const void *arg);
          // Handle timeouts.
             
15.       virtual int handle_signal (int signum,
16.                                  siginfo_t *,
17.                                  ucontext_t *);
          // Handle timeouts.
             
18.       sig_atomic_t finished_;
          // Keeps track of whether we're done.
        };
             
19.     int 
20.     Connection_Handler::open (void *)
        {
21.       ACE_DEBUG ((LM_DEBUG, &quot;(%P|%t) in open()\n&quot;));
             
          // Create an Active Object.
22.       return this-&gt;activate (THR_NEW_LWP);
        }
             
23.     Connection_Handler::close (u_long)
        {
24.       ACE_DEBUG ((LM_DEBUG, &quot;(%P|%t) in close()\n&quot;));
             
          // Shut ourself down.
25.       this-&gt;destroy ();
26.       return 0;
        }
             
27.     int 
28.     Connection_Handler::svc (void)
        {
29.       ACE_DEBUG ((LM_DEBUG, &quot;(%P|%t) in svc()\n&quot;));
             
30.       this-&gt;finished_ = 0;
             
          // Create our own personal Reactor just for this thread.  Note that 
          // we create this on the stack of the thread since it's only used 
          // for the duration of this connection!
             
31.       ACE_Reactor reactor;
             
          // Each &lt;ACE_Svc_Handler&gt; has its own &lt;ACE_Reactor *&gt;.  By default, this 
          // points to the &lt;Acceptor's&gt; Reactor.  However, we can point it to our 
          // local Reactor, which is what we do in this case.
32.       this-&gt;reactor (&amp;reactor);
             
          // Register ourselves to handle input in this thread without 
          // blocking.
33.       if (this-&gt;reactor ()-&gt;register_handler 
34.           (this, ACE_Event_Handler::READ_MASK) == -1)
35.         ACE_ERROR_RETURN ((LM_ERROR, &quot;can' (%P|%t) t register with reactor\n&quot;), -1);
             
          // Schedule a timer.
36.       else if (this-&gt;reactor ()-&gt;schedule_timer 
37.                (this, 
38.                 (const void *) this, 
39.                 ACE_Time_Value (2), 
40.                 ACE_Time_Value (2)) == -1)
41.         ACE_ERROR_RETURN ((LM_ERROR, &quot;(%P|%t) can't register with reactor\n&quot;), -1);
42.       else
43.         ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) connected with client\n&quot;));
             
          // Keep looping until we receive SIGQUIT or the client shutsdown.
             
44.       while (this-&gt;finished_ == 0)
            {
45.           ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) handling events\n&quot;)); 
46.           this-&gt;reactor ()-&gt;handle_events ();
            }
             
          // Cancel all pending timeouts.
47.       ACE_Service_Config::reactor ()-&gt;cancel_timer (this);
             
          // Remove ourselves from the Reactor. 
48.       this-&gt;reactor ()-&gt;remove_handler 
49.         (this, ACE_Event_Handler::READ_MASK | ACE_Event_Handler::DONT_CALL);
             
          // Zero-out the Reactor field so it isn't accessed later on. 
50.       this-&gt;reactor (0);
             
51.       ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) exiting svc\n&quot;)); 
52.       return 0;
        } 
             
53.     int 
54.     Connection_Handler::handle_close (ACE_HANDLE, 
55.                                       ACE_Reactor_Mask)
        {
56.       ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) in handle_close \n&quot;));
             
          // Signal the svc() event loop to shut down. 
57.       this-&gt;finished_ = 1;
58.       return 0;
        }
             
59.     int 
60.     Connection_Handler::handle_input (ACE_HANDLE) 
        {
61.       char buf[BUFSIZ];
             
62.       ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) handle_input\n&quot;));
             
63.       switch (this-&gt;peer ().recv (buf, sizeof buf))
            {
64.         case -1:
65.           ACE_ERROR_RETURN ((LM_ERROR, &quot; (%P|%t) %p bad read\n&quot;, &quot;client logger&quot;),
66.     -1);
67.         case 0:
68.           ACE_ERROR_RETURN ((LM_ERROR, 
69.                              &quot; (%P|%t) closing log daemon (fd = %d)\n&quot;,
70.     this-&gt;get_handle ()), -1);
71.         default:
72.           if (buf[0] == EOF)
73.             ACE_ERROR_RETURN ((LM_ERROR, 
74.                                &quot; (%P|%t) closing log daemon (fd = %d)\n&quot;,
75.     this-&gt;get_handle ()), -1);
76.           else
77.             ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) from client: %s&quot;, buf));
            }
             
78.       return 0;
        }
             
79.     int 
80.     Connection_Handler::handle_signal (int signum,
81.                                        siginfo_t *,
82.                                        ucontext_t *)
        {
83.       ACE_DEBUG ((LM_DEBUG, &quot;received signal %S\n&quot;, signum)); 
84.       this-&gt;finished_ = 1;
85.       return 0;
        }
             
86.     int 
87.     Connection_Handler::handle_timeout (const ACE_Time_Value &amp;tv, 
88.                                         const void *arg)
        {
89.       ACE_ASSERT (arg == this);
90.       ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) handling timeout from this = %u\n&quot;, this)); 
91.       return 0;
        }
             
        // Define an Acceptor for the &lt;Connection_Handler&gt;.
             
92.     typedef ACE_Acceptor &lt;Connection_Handler, ACE_SOCK_ACCEPTOR&gt; 
93.             Connection_Acceptor;
             
94.     int 
95.     main (int argc, char *argv[])
        {
96.       ACE_Service_Config daemon (argv[0]);
             
97.       u_short port = argc &gt; 1 ? ACE_OS::atoi (argv[1]) : ACE_DEFAULT_SERVER_PORT;
             
98.       ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) in main\n&quot;));
             
          // Acceptor factory.
99.       Connection_Acceptor peer_acceptor;
             
          // Create an adapter to end the event loop. 
100.      ACE_Sig_Adapter sa ((ACE_Sig_Handler_Ex)
101.    ACE_Service_Config::end_reactor_event_loop);
             
          // Register the signal handler adapter.
102.      if (daemon.reactor ()-&gt;register_handler (SIGINT, &amp;sa) == -1)
103.        ACE_ERROR_RETURN ((LM_ERROR, &quot;%p\n&quot;, &quot;register_handler&quot;), -1);
             
          // Open the Acceptor.
104.      else if (peer_acceptor.open (ACE_INET_Addr (port),
105.                                   daemon.reactor ()) == -1)
106.        ACE_ERROR_RETURN ((LM_ERROR, &quot;%p\n&quot;, &quot;open&quot;), -1);
             
107.      ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) starting up connection server\n&quot;));
             
          // Perform connection service until we receive SIGINT.
             
108.      while (daemon.reactor_event_loop_done () == 0)
109.        daemon.run_reactor_event_loop ();
             
110.      ACE_DEBUG ((LM_DEBUG, &quot; (%P|%t) shutting down connection server\n&quot;));
             
111.      return 0;
        }
</PRE>
</UL>

<P>
<HR WIDTH="100%"></P>

<P>Here's a summary of how this solution works:</P>

<UL>
<P><TT>Main</TT>() : </P>

<P>The <TT>main</TT> function of this active object solution is similar
to the previously introduced solution in idea, but as you probrably noted
the implementation is carried out differently. Both solutions use the concept
of an acceptor listening on a certain port, which instantiate an object
to handle the processing of data over the connection. However , the solution
most recently described uses an object of type <I>ACE_Service_Config</I>
which automatically provides a reactor, and a lot of method calls which
can be used to control the reactor (for example method call end_reactor_event_loop
stops the reactor iterating through its registered event handlers). In
our first solution however, we had to explicitly create a reactor and write
the function which ran and terminated the reactor. Notice also that the
acceptor in the first solution had to be explicitly registered with
our global reactor , whereas this is done transparently in the second solution
by passing the address of the reactor into the open call of the <I>ACE_Acceptor</I>
object. </P>

<P>Connection handling : </P>

<P>Two alternative methods have been introduced for handling a connection
once a request for connection has been received by the <I>ACE_Acceptor</I>
object. In our first solution, we used the <I>ACE_Thread</I> class to explicitly
spawn a new thread which instantiates a reactor automatically when the
thread is initialised. As you probrably remember however , we had to declare
a static function so that we could pass the address of the <I>Logging_Handler
</I>object to the function so we had a run time reference to what object was
calling the thread. In the second solution presented, the use of active
objects allows us to bypass the programming overhead of spawning the thread by simply
activating the object when it is ready to run. This is acheived by the call
to member function <TT>activate</TT> which automatically creates a new
thread and causes the svc function of
 the <I>Logging_Handler</I> object to be called.
Since the <I>Logging_Handler</I> object is running in an independent
thread, we dont have to worry about keeping track of a static thread function,
which was necessary in the first solution presented. However, as mentioned
in the introduction, the active object solution is a specific solution
for a single reactor per thread each having one connection. Unlike the
first solution, it does not cater for the reactor having more than once
<I>Logging_Handler</I> objects to iterate through, which is what we will implement
in future tutorials. (Note that an active object could be used to create the
multiple-connections per reactor scenario.  It is just this example which
does not do so.)
</P>
</UL>

<OL>
<OL>
<OL>
<OL>
<OL>
<OL>
<P>[<A HREF="../">Tutorial Index</A>] [<A HREF="page06.html">Previous
Page</A>]</P>
</OL>
</OL>
</OL>
</OL>
</OL>
</OL>

</BODY>
</HTML>