Merge pull request #2216 from jwillemsen/jwi-cxxversionchecks
[ACE_TAO.git] / ACE / examples / APG / ThreadSafety / Barrier.cpp
blob2bca398321fa8047e2aa0bdf6c24f13cfd9250a0
1 #include "ace/config-lite.h"
2 #if defined (ACE_HAS_THREADS)
4 #include "ace/OS_NS_stdlib.h"
5 #include "ace/OS_NS_time.h"
6 #include "ace/Task.h"
7 #include "ace/Synch.h"
9 // Listing 2 code/ch14
10 class HA_CommandHandler : public ACE_Task<ACE_MT_SYNCH>
12 public:
13 enum { N_THREADS = 5 };
15 HA_CommandHandler (ACE_Barrier& startup_barrier,
16 ACE_Barrier &shutdown_barrier)
17 : startup_barrier_(startup_barrier),
18 shutdown_barrier_(shutdown_barrier)
19 { }
21 void initialize_handler ();
22 int handle_command_requests ();
24 int svc ()
26 initialize_handler ();
27 startup_barrier_.wait ();
28 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t: %D) Started\n")));
30 while (handle_command_requests () > 0)
33 shutdown_barrier_.wait ();
34 ACE_DEBUG ((LM_DEBUG, ACE_TEXT ("(%t: %D) Ended\n")));
36 return 0;
39 private:
40 ACE_Barrier& startup_barrier_;
41 ACE_Barrier& shutdown_barrier_;
43 // Listing 2
45 void
46 HA_CommandHandler::initialize_handler ()
48 ACE_Time_Value tv (0, ACE_OS::rand () * 100);
49 timespec_t t = (timespec_t)tv;
50 ACE_OS::nanosleep (&t);
53 int
54 HA_CommandHandler::handle_command_requests ()
56 ACE_Time_Value tv (0, ACE_OS::rand () * 100);
57 timespec_t t = (timespec_t)tv;
59 // Simulate work.
60 ACE_OS::nanosleep (&t);
62 return -1;
65 // Listing 1 code/ch14
66 int ACE_TMAIN (int, ACE_TCHAR *[])
68 ACE_Barrier startup_barrier (HA_CommandHandler::N_THREADS);
69 ACE_Barrier shutdown_barrier (HA_CommandHandler::N_THREADS);
71 HA_CommandHandler handler (startup_barrier, shutdown_barrier);
72 handler.activate (THR_NEW_LWP | THR_JOINABLE,
73 HA_CommandHandler::N_THREADS);
74 handler.wait ();
75 return 0;
77 // Listing 1
79 #else
80 #include "ace/OS_main.h"
81 #include "ace/OS_NS_stdio.h"
83 int ACE_TMAIN (int, ACE_TCHAR *[])
85 ACE_OS::puts (ACE_TEXT ("This example requires threads."));
86 return 0;
89 #endif /* ACE_HAS_THREADS */