1 // This test shows the use of an ACE_Auto_Event as a signaling
2 // mechanism. Two threads are created (one a reader, the other a
3 // writer). The reader waits till the writer has completed
4 // calculations. Upon waking up the reader prints the data calculated
5 // by the writer. The writer thread calculates the value and signals
6 // the reader when the calculation completes.
8 #include "ace/OS_NS_unistd.h"
9 #include "ace/OS_main.h"
10 #include "ace/Service_Config.h"
11 #include "ace/Auto_Event.h"
12 #include "ace/Singleton.h"
13 #include "ace/Thread_Manager.h"
15 #if defined (ACE_HAS_THREADS)
16 // Shared event between reader and writer. The ACE_Thread_Mutex is
17 // necessary to make sure that only one ACE_Auto_Event is created.
18 // The default constructor for ACE_Auto_Event sets it initially into
19 // the non-signaled state.
21 typedef ACE_Singleton
<ACE_Auto_Event
, ACE_Thread_Mutex
> EVENT
;
23 // work time for writer
30 // Shared data via a reference.
31 int& data
= *(int *) arg
;
33 // Wait for writer to complete.
35 ACE_DEBUG ((LM_DEBUG
, "(%t) reader: waiting......\n"));
37 if (EVENT::instance ()->wait () == -1)
39 ACE_ERROR ((LM_ERROR
, "thread wait failed"));
44 ACE_DEBUG ((LM_DEBUG
, "(%t) reader: value of data is: %d\n", data
));
53 int& data
= *(int *) arg
;
56 ACE_DEBUG ((LM_DEBUG
, "(%t) writer: working for %d secs\n", work_time
));
57 ACE_OS::sleep (work_time
);
63 ACE_DEBUG ((LM_DEBUG
, "(%t) writer: calculation complete, waking reader\n"));
65 if (EVENT::instance ()->signal () == -1)
67 ACE_ERROR ((LM_ERROR
, "thread signal failed"));
75 ACE_TMAIN (int argc
, ACE_TCHAR
**argv
)
77 // Shared data: set by writer, read by reader.
80 // Work time for writer.
81 work_time
= argc
== 2 ? ACE_OS::atoi (argv
[1]) : 5;
84 ACE_Thread_Manager
& tm
= *ACE_Thread_Manager::instance ();
86 // Create reader thread.
87 if (tm
.spawn ((ACE_THR_FUNC
) reader
, (void *) &data
) == -1)
88 ACE_ERROR_RETURN ((LM_ERROR
, "thread create for reader failed"), -1);
90 // Create writer thread.
91 if (tm
.spawn ((ACE_THR_FUNC
) writer
, (void *) &data
) == -1)
92 ACE_ERROR_RETURN ((LM_ERROR
, "thread create for writer failed"), -1);
96 ACE_ERROR_RETURN ((LM_ERROR
, "thread wait failed"), -1);
98 ACE_DEBUG ((LM_ERROR
, "graceful exit\n"));
103 ACE_SINGLETON_TEMPLATE_INSTANTIATE(ACE_Singleton
, ACE_Auto_Event
, ACE_Thread_Mutex
);
108 ACE_TMAIN (int, ACE_TCHAR
*[])
110 ACE_ERROR ((LM_ERROR
, "threads not supported on this platform\n"));
113 #endif /* ACE_HAS_THREADS */