summaryrefslogtreecommitdiff
path: root/gdb/gdbsupport/thread_pool.c
blob: a78edeaef7ac32a7955367a78de7d559b9ea2930 (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
#include "thread_pool.h"

namespace gdb {

thread_pool::~thread_pool ()
{
  {
    std::lock_guard<std::mutex> guard (m_tasks_mutex);
    m_shutdown = true;
    m_tasks_cv.notify_all ();
  }
  for (auto& t : m_threads)
    t.join();
}

void
thread_pool::start (size_t num_threads)
{
  for (size_t i = 0; i < num_threads; ++i)
    {
      m_threads.emplace_back (&thread_pool::thread_function, this);
    }
  m_started = true;
}


void
thread_pool::thread_function ()
{
  while (!m_shutdown)
    {
      task t;
      {
	std::unique_lock<std::mutex> guard (m_tasks_mutex);
	if (m_shutdown)
	  break;
	if (m_tasks.empty ())
	  m_tasks_cv.wait (guard);
	if (m_shutdown)
	  break;
	if (m_tasks.empty ())
	  continue;
	t = std::move (m_tasks.front());
	m_tasks.pop();
      }
      t ();
    }
}

}