xtd 0.2.0
Loading...
Searching...
No Matches
interlocked_decrement.cpp

Shows how to use xtd::threading::interlocked::decrement and xtd::threading::interlocked::increment methods.

#include <xtd/threading/interlocked>
#include <xtd/threading/thread>
#include <xtd/console>
#include <xtd/startup>
using namespace xtd;
using namespace xtd::threading;
namespace interlocked_decrement_example {
class my_interlocked_decrement_class {
private:
class count_class {
public:
inline static int unsafe_instance_count = 0;
inline static int safe_instance_count = 0;
count_class() {
unsafe_instance_count++;
interlocked::increment(safe_instance_count);
}
~count_class() {
unsafe_instance_count--;
interlocked::decrement(safe_instance_count);
}
};
public:
static auto main() {
auto thread1 = thread {thread_method};
auto thread2 = thread {thread_method};
thread1.start();
thread2.start();
thread1.join();
thread2.join();
console::write_line("unsafe_instance_count: {}\nsafe_instance_count: {}", count_class::unsafe_instance_count, count_class::safe_instance_count);
}
private:
static void thread_method() {
auto cc = count_class {};
// Create 100000 instances of count_class.
for (auto i = 0; i < 100000; ++i)
cc = count_class {};
}
};
}
startup_(interlocked_decrement_example::my_interlocked_decrement_class::main);
// This code produces the following output :
//
// unsafe_instance_count: 253
// safe_instance_count: 0
Creates and controls a thread, sets its priority, and gets its status.
Definition thread.h:43
void start()
Causes the operating system to change the state of the current instance to xtd::threading::thread_sta...
#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:175
The xtd::threading namespace provides classes and interfaces that enable multithreaded programming....
Definition abandoned_mutex_exception.h:11
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10