aboutsummaryrefslogtreecommitdiff
path: root/build2/context.ixx
blob: aee7e320946f38a6ad1002d31a6d735085111a0c (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
// file      : build2/context.ixx -*- C++ -*-
// copyright : Copyright (c) 2014-2017 Code Synthesis Ltd
// license   : MIT; see accompanying LICENSE file

namespace build2
{
  // phase_lock
  //
  inline phase_lock::
  phase_lock (run_phase p)
      : p (p)
  {
    if (phase_lock* l = instance)
      assert (l->p == p);
    else
    {
      phase_mutex::instance.lock (p);
      instance = this;

      //text << this_thread::get_id () << " phase acquire " << p;
    }
  }

  inline phase_lock::
  ~phase_lock ()
  {
    if (instance == this)
    {
      instance = nullptr;
      phase_mutex::instance.unlock (p);

      //text << this_thread::get_id () << " phase release " << p;
    }
  }

  // phase_unlock
  //
  inline phase_unlock::
  phase_unlock (bool u)
      : l (u ? phase_lock::instance : nullptr)
  {
    if (u)
    {
      phase_lock::instance = nullptr;
      phase_mutex::instance.unlock (l->p);

      //text << this_thread::get_id () << " phase unlock  " << l->p;
    }
  }

  inline phase_unlock::
  ~phase_unlock ()
  {
    if (l != nullptr)
    {
      phase_mutex::instance.lock (l->p);
      phase_lock::instance = l;

      //text << this_thread::get_id () << " phase lock    " << l->p;
    }
  }

  // phase_switch
  //
  inline phase_switch::
  phase_switch (run_phase n)
      : o (phase), n (n)
  {
    phase_mutex::instance.relock (o, n);
    phase_lock::instance->p = n;

    if (n == run_phase::load) // Note: load lock is exclusive.
      load_generation++;

    //text << this_thread::get_id () << " phase switch  " << o << " " << n;
  }

  inline phase_switch::
  ~phase_switch ()
  {
    phase_mutex::instance.relock (n, o);
    phase_lock::instance->p = o;

    //text << this_thread::get_id () << " phase restore " << n << " " << o;
  }

  // wait_guard
  //
  inline wait_guard::
  wait_guard (atomic_count& tc, bool p)
      : wait_guard (0, tc, p)
  {
  }

  inline wait_guard::
  wait_guard (size_t sc, atomic_count& tc, bool p)
      : start_count (sc), task_count (&tc), phase (p)
  {
  }

  inline wait_guard::
  ~wait_guard () noexcept (false)
  {
    if (task_count != nullptr)
      wait ();
  }

  inline void wait_guard::
  wait ()
  {
    phase_unlock u (phase);
    sched.wait (start_count, *task_count);
    task_count = nullptr;
  }
}