summaryrefslogtreecommitdiff
path: root/examples/Threads/test_barrier1.cpp
blob: d868fb0dfd4df706f236dbef215ce0f7677cdc4e (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
// This test program illustrates how the ACE barrier synchronization
// $Id$

// mechanisms work.

#include "ace/Log_Msg.h"
#include "ace/Synch.h"
#include "ace/Thread_Manager.h"
#include "ace/Service_Config.h"

#if defined (ACE_HAS_THREADS)

struct Tester_Args
  // = TITLE
  //     These arguments are passed into each test thread.
{
  Tester_Args (ACE_Barrier &tb, int i)
    : tester_barrier_ (tb), 
      n_iterations_ (i) {}

  ACE_Barrier &tester_barrier_;
  // Reference to the tester barrier.  This controls each miteration of
  // the tester function running in every thread.

  int n_iterations_;
  // Number of iterations to run.
};

// Iterate <n_iterations> time printing off a message and "waiting"
// for all other threads to complete this iteration.

static void *
tester (Tester_Args *args)
{
  // Keeps track of thread exit.
  ACE_Thread_Control tc (ACE_Service_Config::thr_mgr ());

  for (int iterations = 1; 
       iterations <= args->n_iterations_;
       iterations++)
    {
      ACE_DEBUG ((LM_DEBUG, "(%t) in iteration %d\n", iterations));

      // Block until all other threads have waited, then continue.
      args->tester_barrier_.wait ();
    }

  return 0;
}

// Default number of threads to spawn.
static const int DEFAULT_ITERATIONS = 5;

int 
main (int argc, char *argv[])
{
  ACE_Service_Config daemon (argv[0]);

  int n_threads = argc > 1 ? ACE_OS::atoi (argv[1]) : ACE_DEFAULT_THREADS;
  int n_iterations = argc > 2 ? ACE_OS::atoi (argv[2]) : DEFAULT_ITERATIONS;

  ACE_Barrier tester_barrier (n_threads);
  
  Tester_Args args (tester_barrier, n_iterations);

  if (ACE_Service_Config::thr_mgr ()->spawn_n 
      (n_threads, ACE_THR_FUNC (tester), 
       (void *) &args, THR_NEW_LWP | THR_DETACHED) == -1)
    ACE_ERROR_RETURN ((LM_ERROR, "%p\n", "spawn_n"), 1);

  // Wait for all the threads to reach their exit point.
  ACE_Service_Config::thr_mgr ()->wait ();

  ACE_DEBUG ((LM_DEBUG, "(%t) done\n"));
  return 0;
}
#else
int 
main (int, char *[])
{
  ACE_ERROR ((LM_ERROR, "threads not supported on this platform\n"));
  return 0;
}
#endif /* ACE_HAS_THREADS */