#include <xtd/threading/mutex>
#include <xtd/threading/thread>
#include <xtd/console>
#include <xtd/startup>
namespace mutex_example {
class program {
public:
static void main() {
for (auto i = 0; i < num_threads; ++i) {
threads.emplace_back(thread_proc);
threads.back().name(ustring::format("thread_{0}", i + 1));
threads.back().start();
}
thread::join_all(threads);
}
static void thread_proc() {
for(auto i = 0; i < num_iterations; ++i)
Use_resource();
}
private:
static void Use_resource() {
console::write_line("{0} is requesting the mutex",
thread::current_thread().name());
mut.wait_one();
console::write_line("{0} has entered the protected area",
thread::current_thread().name());
thread::sleep(500);
console::write_line("{0} is leaving the protected area",
thread::current_thread().name());
mut.release_mutex();
console::write_line("{0} has released the mutex",
thread::current_thread().name());
}
inline static std::vector<thread> threads;
inline static constexpr int num_iterations = 1;
inline static constexpr int num_threads = 3;
};
}
A synchronization primitive that can also be used for interprocess synchronization.
Definition mutex.h:48
#define startup_(main_method)
Defines the entry point to be called when the application loads. Generally this is set either to the ...
Definition startup.h:166
The xtd::threading namespace provides classes and interfaces that enable multithreaded programming....
Definition abandoned_mutex_exception.h:10
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10