Ne.app NeANT
The Ne.app NeANT User module of the NeANT distribution.
mutex.cpp
Go to the documentation of this file.
1
37#include <iostream> // for cout
38#include <rw/_mutex.h> // for __rw::__rw_mutex
39
40#include <examples.h>
41
42
43#ifdef _RWSTD_REENTRANT
44
45// An integer shared amongst multiple threads.
46int shared;
47
48// A mutex used to synchronize updates to shared.
49__rw::__rw_mutex shared_mutex;
50
51// Increment shared by one. Uses a mutex directly.
52void increment_shared ()
53{
54 shared_mutex._C_acquire(); // Lock the mutex.
55 ++shared;
56 shared_mutex._C_release(); // Unlock the mutex.
57}
58
59
60// Decrement shared by one. Uses a mutex guard.
61void decrement_shared ()
62{
63 _RWSTD_MT_GUARD (shared_mutex); // Acquire the lock on shared_mutex.
64 --shared;
65 // The lock on shared is released when destructor is called on guard.
66}
67
68
69int exchange_shared ()
70{
71 int new_value = shared;
72
73 new_value *= new_value;
74
75 // atomically assign new_value to shared and return shared's old value
76 int old_value = _RWSTD_ATOMIC_SWAP (shared, new_value, shared_mutex);
77
78 return old_value;
79}
80
81#endif // _RWSTD_REENTRANT
82
83
84int main()
85{
86#ifdef _RWSTD_REENTRANT
87
88 increment_shared();
89 decrement_shared();
90
91 std::cout << "Multi Threading enabled" << std::endl;
92
93#else // if !defined (_RWSTD_REENTRANT)
94
95 std::cout << "Multi Threading not enabled" << std::endl;
96
97#endif // _RWSTD_REENTRANT
98
99 return 0;
100}
const std::string shared[nstrings]
#define _RWSTD_ATOMIC_SWAP(x, y, ignore)
Definition _defs.h:701
#define _RWSTD_MT_GUARD(ignore)
Definition _defs.h:695
int main()
Definition mutex.cpp:84