#include <xtd/threading/auto_reset_event>
#include <xtd/threading/interlocked>
#include <xtd/threading/thread>
#include <xtd/threading/thread_pool>
#include <xtd/console>
#include <xtd/lock>
#include <xtd/startup>
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 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);
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);
Supports all classes in the xtd class hierarchy and provides low-level services to derived classes....
Definition object.hpp:42
Represents a thread synchronization event that, when signaled, resets automatically after releasing a...
Definition auto_reset_event.hpp:36
virtual bool wait_one()
Blocks the current thread until the current xtd::threading::wait_handle receives a signal.
#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:175
#define lock_(object)
The lock_ keyword marks a statement block as a critical section by obtaining the mutual-exclusion loc...
Definition lock.hpp:85
The xtd::threading namespace provides classes and interfaces that enable multithreaded programming....
Definition abandoned_mutex_exception.hpp:11
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.hpp:10