| Line |
Branch |
Exec |
Source |
| 1 |
|
|
#include <unistd.h> |
| 2 |
|
|
#include <atomic> |
| 3 |
|
|
#include <iostream> |
| 4 |
|
|
#include <thread> |
| 5 |
|
|
#include <vector> |
| 6 |
|
|
|
| 7 |
|
|
#include "shared_memory/condition_variable.hpp" |
| 8 |
|
|
#include "shared_memory/lock.hpp" |
| 9 |
|
|
#include "shared_memory/mutex.hpp" |
| 10 |
|
|
|
| 11 |
|
|
#define MUTEX_ID "sm_cond_var_demo_mutex" |
| 12 |
|
|
#define CV_SEGMENT_ID "sm_cond_var_demo_segment" |
| 13 |
|
|
#define RUNNING_SEGMENT_ID "sm_running_demo_segment" |
| 14 |
|
|
#define RUNNING_OBJECT_ID "sm_running_demo_object" |
| 15 |
|
|
#define VALUE 2 |
| 16 |
|
|
|
| 17 |
|
✗ |
bool should_run() |
| 18 |
|
|
{ |
| 19 |
|
|
bool running; |
| 20 |
|
✗ |
shared_memory::get<bool>(RUNNING_SEGMENT_ID, RUNNING_OBJECT_ID, running); |
| 21 |
|
✗ |
return running; |
| 22 |
|
|
} |
| 23 |
|
|
|
| 24 |
|
✗ |
void update_vector() |
| 25 |
|
|
{ |
| 26 |
|
✗ |
std::vector<int> v(1000000); |
| 27 |
|
✗ |
shared_memory::Mutex::clean(MUTEX_ID); |
| 28 |
|
✗ |
shared_memory::clear_shared_memory(RUNNING_SEGMENT_ID); |
| 29 |
|
✗ |
shared_memory::Mutex mutex(MUTEX_ID); |
| 30 |
|
✗ |
shared_memory::ConditionVariable condition(CV_SEGMENT_ID, true); |
| 31 |
|
✗ |
shared_memory::set<bool>(RUNNING_SEGMENT_ID, RUNNING_OBJECT_ID, false); |
| 32 |
|
|
|
| 33 |
|
✗ |
std::cout << "\nwaiting for pong ...\n"; |
| 34 |
|
|
|
| 35 |
|
✗ |
bool first_iteration = true; |
| 36 |
|
|
|
| 37 |
|
✗ |
while (first_iteration || should_run()) |
| 38 |
|
|
{ |
| 39 |
|
✗ |
first_iteration = false; |
| 40 |
|
|
|
| 41 |
|
|
{ |
| 42 |
|
✗ |
shared_memory::Lock lock(mutex); |
| 43 |
|
✗ |
condition.wait(lock); |
| 44 |
|
|
|
| 45 |
|
✗ |
std::cout << "PING "; |
| 46 |
|
✗ |
for (unsigned int i = 0; i < v.size(); i++) |
| 47 |
|
|
{ |
| 48 |
|
✗ |
v[i] = VALUE; |
| 49 |
|
|
} |
| 50 |
|
|
|
| 51 |
|
✗ |
usleep(500); |
| 52 |
|
|
|
| 53 |
|
✗ |
for (unsigned int i = 0; i < v.size(); i++) |
| 54 |
|
|
{ |
| 55 |
|
✗ |
if (v[i] != VALUE) |
| 56 |
|
|
{ |
| 57 |
|
✗ |
std::cout << "\n--- damn, the vector was not locked !\n"; |
| 58 |
|
✗ |
break; |
| 59 |
|
|
} |
| 60 |
|
✗ |
if (i < 10) |
| 61 |
|
|
{ |
| 62 |
|
✗ |
std::cout << " " << v[i]; |
| 63 |
|
|
} |
| 64 |
|
|
} |
| 65 |
|
✗ |
std::cout << "\n"; |
| 66 |
|
|
} |
| 67 |
|
|
|
| 68 |
|
✗ |
condition.notify_one(); |
| 69 |
|
|
} |
| 70 |
|
|
|
| 71 |
|
✗ |
shared_memory::clear_shared_memory(RUNNING_SEGMENT_ID); |
| 72 |
|
|
} |
| 73 |
|
|
|
| 74 |
|
✗ |
int main() |
| 75 |
|
|
{ |
| 76 |
|
✗ |
update_vector(); |
| 77 |
|
|
} |
| 78 |
|
|
|