summaryrefslogtreecommitdiff
path: root/examples/thread/dispatcher.cc
blob: 5f83c44cac6b8a4cdc4edb07a33b80a0fdf328f6 (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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*
 * Glib::Dispatcher example -- cross thread signalling
 * by Daniel Elstner  <daniel.kitta@gmail.com>
 *
 * modified to only use glibmm
 * by J. Abelardo Gutierrez <jabelardo@cantv.net>
 *
 * Copyright (c) 2002-2003  Free Software Foundation
 */

#include <glibmm.h>

#include <algorithm>
#include <functional>
#include <iostream>
#include <vector>

namespace
{

/*
 * Note that it does not make sense for this class to inherit from
 * sigc::trackable, as doing so would only give a false sense of security.
 * Once the thread launch has been triggered, the object has to stay alive
 * until the thread has been joined again.  The code running in the thread
 * assumes the existence of the object.  If it is destroyed earlier, the
 * program will crash, with sigc::trackable or without it.
 */
class ThreadProgress
{
public:
  explicit ThreadProgress(int id);
  virtual ~ThreadProgress();

  int  id() const;
  void launch();
  void join();
  bool unfinished() const;

  sigc::signal<void>& signal_finished();

private:
  enum { ITERATIONS = 100 };

  // Note that the thread does not write to the member data at all.  It only
  // reads signal_increment_, which is only written to before the thread is
  // launched.  Therefore, no locking is required.
  Glib::Threads::Thread*       thread_;
  int                 id_;
  unsigned int        progress_;
  Glib::Dispatcher    signal_increment_;
  sigc::signal<void>  signal_finished_;

  void progress_increment();
  void thread_function();
};

class Application : public sigc::trackable
{
public:
  Application();
  virtual ~Application();

  void run();

private:
  Glib::RefPtr<Glib::MainLoop>  main_loop_;
  std::vector<ThreadProgress*>  progress_threads_;

  void launch_threads();
  void on_progress_finished(ThreadProgress* thread_progress);
};

template <class T>
class DeletePtr : public std::unary_function<void, T>
{
public:
  void operator()(T ptr) const { delete ptr; }
};

ThreadProgress::ThreadProgress(int id)
:
  thread_   (nullptr),
  id_       (id),
  progress_ (0)
{
  // Connect to the cross-thread signal.
  signal_increment_.connect(sigc::mem_fun(*this, &ThreadProgress::progress_increment));
}

ThreadProgress::~ThreadProgress()
{
  // It is an error if the thread is still running at this point.
  g_return_if_fail(thread_ == nullptr);
}

int ThreadProgress::id() const
{
  return id_;
}

void ThreadProgress::launch()
{
  // Create a joinable thread.
  thread_ = Glib::Threads::Thread::create(sigc::mem_fun(*this, &ThreadProgress::thread_function));
}

void ThreadProgress::join()
{
  thread_->join();
  thread_ = 0;
}

bool ThreadProgress::unfinished() const
{
  return (progress_ < ITERATIONS);
}

sigc::signal<void>& ThreadProgress::signal_finished()
{
  return signal_finished_;
}

void ThreadProgress::progress_increment()
{
  ++progress_;
  std::cout << "Thread " << id_ << ": " << progress_ << '%' << std::endl;

  if (progress_ >= ITERATIONS)
    signal_finished_();
}

void ThreadProgress::thread_function()
{
  Glib::Rand rand;

  for (auto i = 0; i < ITERATIONS; ++i)
  {
    Glib::usleep(rand.get_int_range(2000, 20000));

    // Tell the main thread to increment the progress value.
    signal_increment_();
  }
}

Application::Application()
:
  main_loop_        (Glib::MainLoop::create()),
  progress_threads_ (5)
{
  try
  {
    for (std::vector<ThreadProgress*>::size_type i = 0; i < progress_threads_.size(); ++i)
    {
      const auto progress = new ThreadProgress(i + 1);
      progress_threads_[i] = progress;

      progress->signal_finished().connect(
          sigc::bind<1>(sigc::mem_fun(*this, &Application::on_progress_finished), progress));
    }
  }
  catch (...)
  {
    // In your own code, you should preferably use a smart pointer
    // to ensure exception safety.
    std::for_each(progress_threads_.begin(), progress_threads_.end(),
                  DeletePtr<ThreadProgress*>());
    throw;
  }
}

Application::~Application()
{
  std::for_each(progress_threads_.begin(), progress_threads_.end(),
                DeletePtr<ThreadProgress*>());
}

void Application::run()
{
  // Install a one-shot idle handler to launch the threads.
  Glib::signal_idle().connect_once(sigc::mem_fun(*this, &Application::launch_threads));

  main_loop_->run();
}

void Application::launch_threads()
{
  std::cout << "Launching " << progress_threads_.size() << " threads:" << std::endl;

  std::for_each(progress_threads_.begin(), progress_threads_.end(),
                std::mem_fun(&ThreadProgress::launch));
}

void Application::on_progress_finished(ThreadProgress* thread_progress)
{
  thread_progress->join();

  std::cout << "Thread " << thread_progress->id() << ": finished." << std::endl;

  // Quit if it was the last thread to be joined.
  if (std::find_if(progress_threads_.begin(), progress_threads_.end(),
                   std::mem_fun(&ThreadProgress::unfinished)) == progress_threads_.end())
  {
    main_loop_->quit();
  }
}

} // anonymous namespace

int main(int, char**)
{
  Glib::init();

  Application application;
  application.run();

  return 0;
}