#include <xtd/xtd>
namespace monitor_lock_example {
class sync_resource : public object {
public:
void access() {
console::write_line("Starting synchronized resource access on thread #{0}",
thread::current_thread().managed_thread_id());
if (thread::current_thread().managed_thread_id() % 2 == 0)
thread::sleep(2000);
thread::sleep(200);
console::write_line("Stopping synchronized resource access on thread #{0}",
thread::current_thread().managed_thread_id());
}
}
};
class un_sync_resource : public object {
public:
void access() {
console::write_line("Starting unsynchronized resource access on Thread #{0}",
thread::current_thread().managed_thread_id());
if (thread::current_thread().managed_thread_id() % 2 == 0)
thread::sleep(2000);
thread::sleep(200);
console::write_line("Stopping unsynchronized resource access on thread #{0}",
thread::current_thread().managed_thread_id());
}
};
class app {
private:
inline static int num_ops = 0;
inline static auto_reset_event ops_are_done {false};
inline static sync_resource sync_res;
inline static un_sync_resource un_sync_res;
public:
static void main() {
num_ops = 5;
for (int ctr = 0; ctr <= 4; ++ctr)
thread_pool::queue_user_work_item(sync_update_resource);
ops_are_done.wait_one();
console::write_line("\t\nAll synchronized operations have completed.\n");
num_ops = 5;
for (int ctr = 0; ctr <= 4; ctr++)
thread_pool::queue_user_work_item(un_sync_update_resource);
ops_are_done.wait_one();
console::write_line("\t\nAll unsynchronized thread operations have completed.\n");
}
static void sync_update_resource(std::any state) {
sync_res.access();
if (interlocked::decrement(num_ops) == 0)
ops_are_done.set();
}
static void un_sync_update_resource(std::any state) {
un_sync_res.access();
if (interlocked::decrement(num_ops) == 0)
ops_are_done.set();
}
};
}
startup_(monitor_lock_example::app::main);
#define startup_(main_method)
Defines the entry point to be called when the application loads. Generally this is set either to the ...
Definition startup.hpp:168
#define lock_(object)
The lock_ keyword marks a statement block as a critical section by obtaining the mutual-exclusion loc...
Definition lock.hpp:67