File: mt.hh

package info (click to toggle)
zbackup 1.3-1
  • links: PTS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 500 kB
  • ctags: 568
  • sloc: cpp: 4,032; makefile: 2
file content (87 lines) | stat: -rw-r--r-- 1,326 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
// Copyright (c) 2012-2014 Konstantin Isakov <ikm@zbackup.org>
// Part of ZBackup. Licensed under GNU GPLv2 or later + OpenSSL, see LICENSE

#ifndef MT_HH_INCLUDED__
#define MT_HH_INCLUDED__

#include <pthread.h>
#include <stddef.h>

#include "nocopy.hh"

/// Multithreading

class Condition;

class Mutex
{
  friend class Condition;

  pthread_mutex_t mutex;

public:

  Mutex();

  /// Please consider using the Lock class instead
  void lock();

  void unlock();

  ~Mutex();
};

class Lock: NoCopy
{
  Mutex * m;

public:

  Lock( Mutex & mutex ): m( &mutex ) { m->lock(); }

  ~Lock()
  { m->unlock(); }
};

/// Condition variable. Atomically unlocks the given mutex before it suspends
/// waiting for event, and upon the awakening reacquires it
class Condition
{
  pthread_cond_t cond;

public:

  Condition();

  void signal();

  void broadcast();

  /// Mutex must be locked on entrance
  void wait( Mutex & m );

  ~Condition();
};

class Thread
{
public:
  void start();
  void detach();
  void * join();

  virtual ~Thread() {}

protected:
  /// This is the function that is meant to work in a separate thread
  virtual void * threadFunction() throw()=0;

private:
  pthread_t thread;
  static void * __thread_routine( void * );
};

/// Returns the number of CPUs this system has
size_t getNumberOfCpus();

#endif