Welcome to mirror list, hosted at ThFree Co, Russian Federation.

thread_utils.hpp « base - github.com/mapsme/omim.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: 342aab43b06ea3f7936c07825941390f48361454 (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
#pragma once

#include <thread>
#include <vector>

#include "base/macros.hpp"

namespace base
{
namespace threads
{
template <typename Thread = std::thread, typename ThreadContainer = std::vector<Thread>>
class ThreadsJoiner
{
public:
  explicit ThreadsJoiner(ThreadContainer & threads) : m_threads(threads) {}

  ~ThreadsJoiner()
  {
    for (auto & thread : m_threads)
    {
      if (thread.joinable())
        thread.join();
    }
  }

private:
  ThreadContainer & m_threads;
};

// This class can be used in thread pools to store std::packaged_task<> objects.
// std::packaged_task<> isn’t copyable so we have to use std::move().
// This idea is borrowed from the book C++ Concurrency in action by Anthony Williams (Chapter 9).
class FunctionWrapper
{
public:
  template <typename F>
  FunctionWrapper(F && func) : m_impl(new ImplType<F>(std::move(func))) {}

  FunctionWrapper() = default;

  FunctionWrapper(FunctionWrapper && other) : m_impl(std::move(other.m_impl)) {}

  FunctionWrapper & operator=(FunctionWrapper && other)
  {
    m_impl = std::move(other.m_impl);
    return *this;
  }

  void operator()() { m_impl->Call(); }

private:
  struct ImplBase
  {
    virtual ~ImplBase() = default;

    virtual void Call() = 0;
  };

  template <typename F>
  struct ImplType : ImplBase
  {
    ImplType(F && func) : m_func(std::move(func)) {}

    void Call() override { m_func(); }

    F m_func;
  };

  std::unique_ptr<ImplBase> m_impl;

  DISALLOW_COPY(FunctionWrapper);
};
}  // namespace threads
}  // namespace base