File: sec-multithread-example.html

package info (click to toggle)
gtkmm-documentation 4.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 25,772 kB
  • sloc: cpp: 15,541; javascript: 1,208; makefile: 1,080; python: 401; xml: 106; perl: 67; sh: 8
file content (439 lines) | stat: -rw-r--r-- 13,080 bytes parent folder | download
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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="highlight.min.css">
<script src="highlight.min.js"></script><script>
      hljs.configure({languages: ['cpp']});
      hljs.highlightAll();
    </script><title>Example</title>
<link rel="stylesheet" type="text/css" href="style.css">
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot">
<link rel="home" href="index.html" title="Programming with gtkmm 4">
<link rel="up" href="chapter-multi-threaded-programs.html" title="Chapter 29. Multi-threaded programs">
<link rel="prev" href="sec-using-glib-dispatcher.html" title="Using Glib::Dispatcher">
<link rel="next" href="chapter-recommended-techniques.html" title="Chapter 30. Recommended Techniques">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<div class="navheader">
<table width="100%" summary="Navigation header">
<tr><th colspan="3" align="center">Example</th></tr>
<tr>
<td width="20%" align="left">
<a accesskey="p" href="sec-using-glib-dispatcher.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<th width="60%" align="center">Chapter 29. Multi-threaded programs</th>
<td width="20%" align="right"> <a accesskey="n" href="chapter-recommended-techniques.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
</table>
<hr>
</div>
<div class="section">
<div class="titlepage"><div><div><h2 class="title" style="clear: both">
<a name="sec-multithread-example"></a>Example</h2></div></div></div>


<p>
This is an example program with two threads, one GUI thread, like in all
<span class="application">gtkmm</span> programs, and one worker thread. The worker thread is created when you
press the <code class="literal">Start work</code> button. It is deleted when the work is
finished, when you press the <code class="literal">Stop work</code> button, or when you
press the <code class="literal">Quit</code> button.
</p>

<p>
A <code class="classname">Glib::Dispatcher</code> is used for sending notifications
from the worker thread to the GUI thread. The <code class="classname">ExampleWorker</code>
class contains data which is accessed by both threads. This data is protected
by a <code class="classname">std::mutex</code>.
Only the GUI thread updates the GUI.
</p>

<p>
Compiling and linking a multi-threaded program can require special compiler and
linker options. If you use the <span class="application">g++</span> compiler, add the
<code class="literal">-pthread</code> option. Other compilers may require other options.
If you build with <span class="application">meson</span>, it handles the multi-threading
complications for you, if you add <code class="function">dependency('threads')</code>.
</p>

<div class="figure">
<a name="figure-multithread"></a><p class="title"><b>Figure 29.1. Multi-Threaded Program</b></p>
<div class="figure-contents">
  
  <div class="screenshot">
    <div class="mediaobject"><img src="figures/multithread.png" alt="Multi-Threaded Program"></div>
  </div>
</div>
</div>
<br class="figure-break">

<p><a class="ulink" href="https://gitlab.gnome.org/GNOME/gtkmm-documentation/tree/master/examples/book/multithread" target="_top">Source Code</a></p>

<p>File: <code class="filename">examplewindow.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_EXAMPLEWINDOW_H
#define GTKMM_EXAMPLEWINDOW_H

#include &lt;gtkmm.h&gt;
#include "exampleworker.h"

class ExampleWindow : public Gtk::Window
{
public:
  ExampleWindow();

  // Called from the worker thread.
  void notify();

private:
  // Signal handlers.
  void on_start_button_clicked();
  void on_stop_button_clicked();
  void on_quit_button_clicked();

  void update_start_stop_buttons();
  void update_widgets();

  // Dispatcher handler.
  void on_notification_from_worker_thread();

  // Member data.
  Gtk::Box m_VBox;
  Gtk::Box m_ButtonBox;
  Gtk::Button m_ButtonStart;
  Gtk::Button m_ButtonStop;
  Gtk::Button m_ButtonQuit;
  Gtk::ProgressBar m_ProgressBar;
  Gtk::ScrolledWindow m_ScrolledWindow;
  Gtk::TextView m_TextView;

  Glib::Dispatcher m_Dispatcher;
  ExampleWorker m_Worker;
  std::thread* m_WorkerThread;
};

#endif // GTKMM_EXAMPLEWINDOW_H
</code></pre>
<p>File: <code class="filename">exampleworker.h</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#ifndef GTKMM_EXAMPLEWORKER_H
#define GTKMM_EXAMPLEWORKER_H

#include &lt;gtkmm.h&gt;
#include &lt;thread&gt;
#include &lt;mutex&gt;

class ExampleWindow;

class ExampleWorker
{
public:
  ExampleWorker();

  // Thread function.
  void do_work(ExampleWindow* caller);

  void get_data(double* fraction_done, Glib::ustring* message) const;
  void stop_work();
  bool has_stopped() const;

private:
  // Synchronizes access to member data.
  mutable std::mutex m_Mutex;

  // Data used by both GUI thread and worker thread.
  bool m_shall_stop;
  bool m_has_stopped;
  double m_fraction_done;
  Glib::ustring m_message;
};

#endif // GTKMM_EXAMPLEWORKER_H
</code></pre>
<p>File: <code class="filename">examplewindow.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include &lt;iostream&gt;

ExampleWindow::ExampleWindow() :
  m_VBox(Gtk::Orientation::VERTICAL, 5),
  m_ButtonBox(Gtk::Orientation::HORIZONTAL),
  m_ButtonStart("Start work"),
  m_ButtonStop("Stop work"),
  m_ButtonQuit("_Quit", /* mnemonic= */ true),
  m_ProgressBar(),
  m_ScrolledWindow(),
  m_TextView(),
  m_Dispatcher(),
  m_Worker(),
  m_WorkerThread(nullptr)
{
  set_title("Multi-threaded example");
  set_default_size(300, 300);

  m_VBox.set_margin(5);
  set_child(m_VBox);

  // Add the ProgressBar.
  m_VBox.append(m_ProgressBar);

  m_ProgressBar.set_text("Fraction done");
  m_ProgressBar.set_show_text();

  // Add the TextView, inside a ScrolledWindow.
  m_ScrolledWindow.set_child(m_TextView);

  // Only show the scrollbars when they are necessary.
  m_ScrolledWindow.set_policy(Gtk::PolicyType::AUTOMATIC, Gtk::PolicyType::AUTOMATIC);
  m_ScrolledWindow.set_expand();

  m_VBox.append(m_ScrolledWindow);

  m_TextView.set_editable(false);

  // Add the buttons to the ButtonBox.
  m_VBox.append(m_ButtonBox);

  m_ButtonBox.append(m_ButtonStart);
  m_ButtonBox.append(m_ButtonStop);
  m_ButtonBox.append(m_ButtonQuit);
  m_ButtonBox.set_margin(5);
  m_ButtonBox.set_spacing(5);
  m_ButtonStart.set_hexpand(true);
  m_ButtonStart.set_halign(Gtk::Align::END);

  // Connect the signal handlers to the buttons.
  m_ButtonStart.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_start_button_clicked));
  m_ButtonStop.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_stop_button_clicked));
  m_ButtonQuit.signal_clicked().connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_quit_button_clicked));

  // Connect the handler to the dispatcher.
  m_Dispatcher.connect(sigc::mem_fun(*this, &amp;ExampleWindow::on_notification_from_worker_thread));

  // Create a text buffer mark for use in update_widgets().
  auto buffer = m_TextView.get_buffer();
  buffer-&gt;create_mark("last_line", buffer-&gt;end(), /* left_gravity= */ true);

  update_start_stop_buttons();
}

void ExampleWindow::on_start_button_clicked()
{
  if (m_WorkerThread)
  {
    std::cout &lt;&lt; "Can't start a worker thread while another one is running." &lt;&lt; std::endl;
  }
  else
  {
    // Start a new worker thread.
    m_WorkerThread = new std::thread(
      [this]
      {
        m_Worker.do_work(this);
      });
  }
  update_start_stop_buttons();
}

void ExampleWindow::on_stop_button_clicked()
{
  if (!m_WorkerThread)
  {
    std::cout &lt;&lt; "Can't stop a worker thread. None is running." &lt;&lt; std::endl;
  }
  else
  {
   // Order the worker thread to stop.
    m_Worker.stop_work();
    m_ButtonStop.set_sensitive(false);
  }
}

void ExampleWindow::update_start_stop_buttons()
{
  const bool thread_is_running = m_WorkerThread != nullptr;

  m_ButtonStart.set_sensitive(!thread_is_running);
  m_ButtonStop.set_sensitive(thread_is_running);
}

void ExampleWindow::update_widgets()
{
  double fraction_done;
  Glib::ustring message_from_worker_thread;
  m_Worker.get_data(&amp;fraction_done, &amp;message_from_worker_thread);

  m_ProgressBar.set_fraction(fraction_done);

  if (message_from_worker_thread != m_TextView.get_buffer()-&gt;get_text())
  {
    auto buffer = m_TextView.get_buffer();
    buffer-&gt;set_text(message_from_worker_thread);

    // Scroll the last inserted line into view. That's somewhat complicated.
    auto iter = buffer-&gt;end();
    iter.set_line_offset(0); // Beginning of last line
    auto mark = buffer-&gt;get_mark("last_line");
    buffer-&gt;move_mark(mark, iter);
    m_TextView.scroll_to(mark);
    // TextView::scroll_to(iter) is not perfect.
    // We do need a TextMark to always get the last line into view.
  }
}

void ExampleWindow::on_quit_button_clicked()
{
  if (m_WorkerThread)
  {
    // Order the worker thread to stop and wait for it to stop.
    m_Worker.stop_work();
    if (m_WorkerThread-&gt;joinable())
      m_WorkerThread-&gt;join();
  }
  set_visible(false);
}

// notify() is called from ExampleWorker::do_work(). It is executed in the worker
// thread. It triggers a call to on_notification_from_worker_thread(), which is
// executed in the GUI thread.
void ExampleWindow::notify()
{
  m_Dispatcher.emit();
}

void ExampleWindow::on_notification_from_worker_thread()
{
  if (m_WorkerThread &amp;&amp; m_Worker.has_stopped())
  {
    // Work is done.
    if (m_WorkerThread-&gt;joinable())
      m_WorkerThread-&gt;join();
    delete m_WorkerThread;
    m_WorkerThread = nullptr;
    update_start_stop_buttons();
  }
  update_widgets();
}
</code></pre>
<p>File: <code class="filename">exampleworker.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "exampleworker.h"
#include "examplewindow.h"
#include &lt;sstream&gt;
#include &lt;chrono&gt;

ExampleWorker::ExampleWorker() :
  m_Mutex(),
  m_shall_stop(false),
  m_has_stopped(false),
  m_fraction_done(0.0),
  m_message()
{
}

// Accesses to these data are synchronized by a mutex.
// Some microseconds can be saved by getting all data at once, instead of having
// separate get_fraction_done() and get_message() methods.
void ExampleWorker::get_data(double* fraction_done, Glib::ustring* message) const
{
  std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);

  if (fraction_done)
    *fraction_done = m_fraction_done;

  if (message)
    *message = m_message;
}

void ExampleWorker::stop_work()
{
  std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);
  m_shall_stop = true;
}

bool ExampleWorker::has_stopped() const
{
  std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);
  return m_has_stopped;
}

void ExampleWorker::do_work(ExampleWindow* caller)
{
  {
    std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);
    m_has_stopped = false;
    m_fraction_done = 0.0;
    m_message = "";
  } // The mutex is unlocked here by lock's destructor.

  // Simulate a long calculation.
  for (int i = 0; ; ++i) // do until break
  {
    std::this_thread::sleep_for(std::chrono::milliseconds(250));

    {
      std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);

      m_fraction_done += 0.01;

      if (i % 4 == 3)
      {
        std::ostringstream ostr;
        ostr &lt;&lt; (m_fraction_done * 100.0) &lt;&lt; "% done\n";
        m_message += ostr.str();
      }

      if (m_fraction_done &gt;= 1.0)
      {
        m_message += "Finished";
        break;
      }
      if (m_shall_stop)
      {
        m_message += "Stopped";
        break;
      }
    }

    caller-&gt;notify();
  }

  {
    std::lock_guard&lt;std::mutex&gt; lock(m_Mutex);
    m_shall_stop = false;
    m_has_stopped = true;
  }

  caller-&gt;notify();
}
</code></pre>
<p>File: <code class="filename">main.cc</code> (For use with gtkmm 4)</p>
<pre class="programlisting"><code class="code">#include "examplewindow.h"
#include &lt;gtkmm/application.h&gt;

int main(int argc, char* argv[])
{
  auto app = Gtk::Application::create("org.gtkmm.example");

  //Shows the window and returns when it is closed.
  return app-&gt;make_window_and_run&lt;ExampleWindow&gt;(argc, argv);
}
</code></pre>


</div>
<div class="navfooter">
<hr>
<table width="100%" summary="Navigation footer">
<tr>
<td width="40%" align="left">
<a accesskey="p" href="sec-using-glib-dispatcher.html"><img src="icons/prev.png" alt="Prev"></a> </td>
<td width="20%" align="center"><a accesskey="u" href="chapter-multi-threaded-programs.html"><img src="icons/up.png" alt="Up"></a></td>
<td width="40%" align="right"> <a accesskey="n" href="chapter-recommended-techniques.html"><img src="icons/next.png" alt="Next"></a>
</td>
</tr>
<tr>
<td width="40%" align="left" valign="top">Using Glib::Dispatcher </td>
<td width="20%" align="center"><a accesskey="h" href="index.html"><img src="icons/home.png" alt="Home"></a></td>
<td width="40%" align="right" valign="top"> Chapter 30. Recommended Techniques</td>
</tr>
</table>
</div>
</body>
</html>