xtd 0.2.0
Loading...
Searching...
No Matches
xtd::threading::lock_guard Class Referencefinal
Inheritance diagram for xtd::threading::lock_guard:
xtd::object

Definition

Provides a mechanism that synchronizes access to objects with xtd::threading::monitor.

class core_export_ lock_guard final : public xtd::object
Supports all classes in the xtd class hierarchy and provides low-level services to derived classes....
Definition object.h:42
Provides a mechanism that synchronizes access to objects with xtd::threading::monitor.
Definition lock_guard.h:32
#define core_export_
Define shared library export.
Definition core_export.h:13
Inheritance
xtd::object → xtd::lock_guard
Header
#include <xtd/threading/lock_guard>
Namespace
xtd::threading
Library
xtd.core
Examples
The following example uses the xtd::threading::lock_guard class to synchronize access to a single instance of a random number generator represented by the xtd::random class. The example creates ten threads, each of which executes asynchronously on a thread pool thread. Each thread generates 10,000 random numbers, calculates their average, and updates two procedure-level variables that maintain a running total of the number of random numbers generated and their sum. After all threads have executed, these two values are then used to calculate the overall mean.
#include <xtd/collections/generic/list>
#include <xtd/threading/interlocked>
#include <xtd/threading/lock_guard>
#include <xtd/threading/thread>
#include <xtd/console>
#include <xtd/literals>
#include <xtd/random>
#include <xtd/startup>
using namespace xtd;
using namespace xtd::collections::generic;
using namespace xtd::threading;
namespace lock_guard_example {
class program {
public:
static void main() {
auto threads = list<thread> {};
auto rnd = xtd::random {};
auto total = 0_s64;
auto n = 0;
for (auto thread_ctr = 0; thread_ctr < 10; ++thread_ctr)
threads.push_back(thread::start_new([&] {
auto values = std::array<int, 10000> {};
auto thread_total = 0;
auto thread_n = 0;
auto ctr = 0;
// Generate 10,000 random integers
for (ctr = 0; ctr < 10000; ++ctr)
values[ctr] = rnd.next(0, 1001);
}
thread_n = ctr;
for (auto value : values)
thread_total += value;
console::write_line("Mean for task {0,2}: {1:N2} (N={2:N0})",
thread::current_thread().managed_thread_id(),
(thread_total * 1.0) / thread_n, thread_n);
interlocked::add(n, thread_n);
interlocked::add(total, thread_total);
}));
try {
for (auto& thread : threads)
thread.join();
console::write_line("\nMean for all tasks: {0:N2} (N={1:N0})",
(total * 1.0)/n, n);
}
catch (const system_exception& e) {
console::write_line("{0}: {1}", e.get_type().name(), e.message());
}
}
};
}
startup_(lock_guard_example::program::main);
// This example produces output similar to the following:
//
// Mean for task 4: 498.90 (N=10000)
// Mean for task 2: 499.92 (N=10000)
// Mean for task 7: 503.12 (N=10000)
// Mean for task 5: 499.41 (N=10000)
// Mean for task 3: 498.58 (N=10000)
// Mean for task 8: 496.71 (N=10000)
// Mean for task 10: 501.49 (N=10000)
// Mean for task 6: 498.84 (N=10000)
// Mean for task 9: 502.72 (N=10000)
// Mean for task 11: 498.69 (N=10000)
//
// Mean for all tasks: 499.84 (N=100000)
Represents a strongly typed list of objects that can be accessed by index. Provides methods to search...
Definition list.h:71
Represents a pseudo-random number generator, a device that produces a sequence of numbers that meet c...
Definition random.h:40
The exception that is thrown when a method call is invalid for the object's current state.
Definition system_exception.h:18
Creates and controls a thread, sets its priority, and gets its status.
Definition thread.h:43
#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
#define block_scope_(...)
The specified expression is cleared automatically when the scope is ended.
Definition block_scope.h:25
@ n
The N key.
@ e
The E key.
The xtd::collections::generic namespace contains interfaces and classes that define generic collectio...
Definition comparer.h:15
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
Remarks
See xtd::threading::monitor for more information.
Examples
lock_guard.cpp.

Public Constructors

template<typename object_t >
 lock_guard (const object_t &obj)
 Create a xtd::threading::lock_guard object and acquires an exclusive lock on the specified obj.
 

Public Methods

void pulse ()
 Notifies a thread in the waiting queue of a change in the locked object's state.
 
void pulse_all ()
 Notifies all waiting threads of a change in the object's state.
 
bool wait (int32 milliseconds_timeout)
 Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.
 
bool wait (const time_span &timeout)
 Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.
 
bool wait ()
 Releases the lock on an object and blocks the current thread until it reacquires the lock.
 

Additional Inherited Members

- Public Member Functions inherited from xtd::object
 object ()=default
 Create a new instance of the ultimate base class object.
 
virtual bool equals (const object &obj) const noexcept
 Determines whether the specified object is equal to the current object.
 
virtual size_t get_hash_code () const noexcept
 Serves as a hash function for a particular type.
 
virtual type_object get_type () const noexcept
 Gets the type of the current instance.
 
template<typename object_t >
xtd::uptr< object_t > memberwise_clone () const
 Creates a shallow copy of the current object.
 
virtual xtd::string to_string () const noexcept
 Returns a xtd::string that represents the current object.
 
- Static Public Member Functions inherited from xtd::object
template<typename object_a_t , typename object_b_t >
static bool equals (const object_a_t &object_a, const object_b_t &object_b) noexcept
 Determines whether the specified object instances are considered equal.
 
template<typename object_a_t , typename object_b_t >
static bool reference_equals (const object_a_t &object_a, const object_b_t &object_b) noexcept
 Determines whether the specified object instances are the same instance.
 

Constructor & Destructor Documentation

◆ lock_guard()

template<typename object_t >
xtd::threading::lock_guard::lock_guard ( const object_t &  obj)
inlineexplicit

Create a xtd::threading::lock_guard object and acquires an exclusive lock on the specified obj.

Parameters
objThe object on which to acquire the monitor lock.
Remarks
When the xtd::threading::lock_guard destroyed it releases the exclusive lock specified in the constructor.

Member Function Documentation

◆ pulse()

void xtd::threading::lock_guard::pulse ( )

Notifies a thread in the waiting queue of a change in the locked object's state.

Remarks
Only the current owner of the lock can signal a waiting object using xtd::threading::monitor::pulse.
The thread that currently owns the lock on the specified object invokes this method to signal the next thread in line for the lock. Upon receiving the pulse, the waiting thread is moved to the ready queue. When the thread that invoked xtd::threading::monitor::pulse releases the lock, the next thread in the ready queue (which is not necessarily the thread that was pulsed) acquires the lock.
Warning
The xtd::threading::monitor class does not maintain state indicating that the xtd::threading::monitor::pulse method has been called. Thus, if you call xtd::threading::monitor::pulse when no threads are waiting, the next thread that calls xtd::threading::monitor::wait blocks as if xtd::threading::monitor::pulse had never been called. If two threads are using xtd::threading::monitor::pulse and xtd::threading::monitor::wait to interact, this could result in a deadlock. Contrast this with the behavior of the xtd::threading::auto_reset_event class: If you signal an xtd::threading::auto_reset_event by calling its xtd::threading::event_wait_handle::set method, and there are no threads waiting, the xtd::threading::auto_reset_event remains in a signaled state until a thread calls xtd::threading::wait_handle::wait_one, xtd::threading::wait_handle::wait_any, or xtd::threading::wait_handle::wait_all. The xtd::threading::auto_reset_event releases that thread and returns to the unsignaled state.
Remarks
Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
The xtd::threading::monitor::pulse, xtd::threading::monitor::pulse_all, and xtd::threading::monitor::wait methods must be invoked from within a synchronized block of code.
To signal multiple threads, use the xtd::threading::monitor::pulse_all method.

◆ pulse_all()

void xtd::threading::lock_guard::pulse_all ( )

Notifies all waiting threads of a change in the object's state.

Remarks
The thread that currently owns the lock on the specified object invokes this method to signal all threads waiting to acquire the lock on the object. After the signal is sent, the waiting threads are moved to the ready queue. When the thread that invoked xtd::threading::monitor::xtd::threading::monitor::pulse_all releases the lock, the next thread in the ready queue acquires the lock.
Note that a synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
The xtd::threading::monitor::pulse, xtd::threading::monitor::xtd::threading::monitor::pulse_all, and Wait methods must be invoked from within a synchronized block of code.
The remarks for the xtd::threading::monitor::pulse method explain what happens if xtd::threading::monitor::pulse is called when no threads are waiting.
To signal a single thread, use the xtd::threading::monitor::pulse method.

◆ wait() [1/3]

bool xtd::threading::lock_guard::wait ( int32  milliseconds_timeout)

Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.

Parameters
objThe object on which to wait.
milliseconds_timeoutThe number of milliseconds to wait before the thread enters the ready queue.
Returns
true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired.
Exceptions
xtd::threading::synchronization_lock_exceptionxtd::threading::monitor::wait is not invoked from within a synchronized block of code.
Remarks
This method does not return until it reacquires an exclusive lock on the obj parameter.
The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the xtd::threading::monitor::wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the xtd::threading::monitor::wait method again.
When a thread calls xtd::threading::monitor::wait, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes xtd::threading::monitor::pulse_all, or it is the next in the queue and a thread that holds the lock invokes xtd::threading::monitor::pulse. However, if milliseconds_timeout elapses before another thread invokes this object's xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method, the original thread is moved to the ready queue in order to regain the lock.
Note
If xtd::threading::timeout::infinite is specified for the milliseconds_timeout parameter, this method blocks indefinitely unless the holder of the lock calls xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all. If milliseconds_timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
Remarks
The caller executes xtd::threading::monitor::wait once, regardless of the number of times xtd::threading::monitor::enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked xtd::threading::monitor::enter on the object and invokes xtd::threading::monitor::exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls xtd::threading::monitor::enter as many times as necessary to restore the saved xtd::threading::monitor::enter count for the caller. Calling xtd::threading::monitor::wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
Note
A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
Remarks
The xtd::threading::monitor::pulse, xtd::threading::monitor::pulse_all, and Wait methods must be invoked from within a synchronized block of code.
The remarks for the xtd::threading::monitor::pulse method explain what happens if xtd::threading::monitor::pulse is called when no threads are waiting.

◆ wait() [2/3]

bool xtd::threading::lock_guard::wait ( const time_span timeout)

Releases the lock on an object and blocks the current thread until it reacquires the lock. If the specified time-out interval elapses, the thread enters the ready queue.

Parameters
timeoutA xtd::time_span representing the amount of time to wait before the thread enters the ready queue.
Returns
true if the lock was reacquired before the specified time elapsed; false if the lock was reacquired after the specified time elapsed. The method does not return until the lock is reacquired.
Exceptions
xtd::threading::synchronization_lock_exceptionxtd::threading::monitor::wait is not invoked from within a synchronized block of code.
Remarks
This method does not return until it reacquires an exclusive lock on the obj parameter.
The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the xtd::threading::monitor::wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the xtd::threading::monitor::wait method again.
When a thread calls xtd::threading::monitor::wait, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes xtd::threading::monitor::pulse_all, or it is the next in the queue and a thread that holds the lock invokes xtd::threading::monitor::pulse. However, if milliseconds_timeout elapses before another thread invokes this object's xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method, the original thread is moved to the ready queue in order to regain the lock.
Note
If xtd::threading::timeout::infinite is specified for the milliseconds_timeout parameter, this method blocks indefinitely unless the holder of the lock calls xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all. If milliseconds_timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
Remarks
The caller executes xtd::threading::monitor::wait once, regardless of the number of times xtd::threading::monitor::enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked xtd::threading::monitor::enter on the object and invokes xtd::threading::monitor::exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls xtd::threading::monitor::enter as many times as necessary to restore the saved xtd::threading::monitor::enter count for the caller. Calling xtd::threading::monitor::wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
Note
A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
Remarks
The xtd::threading::monitor::pulse, xtd::threading::monitor::pulse_all, and Wait methods must be invoked from within a synchronized block of code.
The remarks for the xtd::threading::monitor::pulse method explain what happens if xtd::threading::monitor::pulse is called when no threads are waiting.

◆ wait() [3/3]

bool xtd::threading::lock_guard::wait ( )

Releases the lock on an object and blocks the current thread until it reacquires the lock.

Returns
true if the call returned because the caller reacquired the lock for the specified object. This method does not return if the lock is not reacquired.
Exceptions
xtd::threading::synchronization_lock_exceptionxtd::threading::monitor::wait is not invoked from within a synchronized block of code.
Remarks
This method does not return until it reacquires an exclusive lock on the obj parameter.
The thread that currently owns the lock on the specified object invokes this method in order to release the object so that another thread can access it. The caller is blocked while waiting to reacquire the lock. This method is called when the caller needs to wait for a state change that will occur as a result of another thread's operations.
The time-out ensures that the current thread does not block indefinitely if another thread releases the lock without first calling the xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method. It also moves the thread to the ready queue, bypassing other threads ahead of it in the wait queue, so that it can reacquire the lock sooner. The thread can test the return value of the xtd::threading::monitor::wait method to determine whether it reacquired the lock prior to the time-out. The thread can evaluate the conditions that caused it to enter the wait, and if necessary call the xtd::threading::monitor::wait method again.
When a thread calls xtd::threading::monitor::wait, it releases the lock and enters the waiting queue. At this point, the next thread in the ready queue (if there is one) is allowed to take control of the lock. The thread that invoked Wait remains in the waiting queue until either a thread that holds the lock invokes xtd::threading::monitor::pulse_all, or it is the next in the queue and a thread that holds the lock invokes xtd::threading::monitor::pulse. However, if milliseconds_timeout elapses before another thread invokes this object's xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all method, the original thread is moved to the ready queue in order to regain the lock.
Note
If xtd::threading::timeout::infinite is specified for the milliseconds_timeout parameter, this method blocks indefinitely unless the holder of the lock calls xtd::threading::monitor::pulse or xtd::threading::monitor::pulse_all. If milliseconds_timeout equals 0, the thread that calls Wait releases the lock and then immediately enters the ready queue in order to regain the lock.
Remarks
The caller executes xtd::threading::monitor::wait once, regardless of the number of times xtd::threading::monitor::enter has been invoked for the specified object. Conceptually, the Wait method stores the number of times the caller invoked xtd::threading::monitor::enter on the object and invokes xtd::threading::monitor::exit as many times as necessary to fully release the locked object. The caller then blocks while waiting to reacquire the object. When the caller reacquires the lock, the system calls xtd::threading::monitor::enter as many times as necessary to restore the saved xtd::threading::monitor::enter count for the caller. Calling xtd::threading::monitor::wait releases the lock for the specified object only; if the caller is the owner of locks on other objects, these locks are not released.
Note
A synchronized object holds several references, including a reference to the thread that currently holds the lock, a reference to the ready queue, which contains the threads that are ready to obtain the lock, and a reference to the waiting queue, which contains the threads that are waiting for notification of a change in the object's state.
Remarks
The xtd::threading::monitor::pulse, xtd::threading::monitor::pulse_all, and Wait methods must be invoked from within a synchronized block of code.
The remarks for the xtd::threading::monitor::pulse method explain what happens if xtd::threading::monitor::pulse is called when no threads are waiting.

The documentation for this class was generated from the following file: