Assuming I have an object A containing
// ...
private List<double> someList = new List<double>();
// ...
public List<double> SomeList
{
get { lock (this) { return someList; } }
}
// ...
would it be thread safe to perform operation on the list as in the code below. Knowing that several operations could be executed simultaneously by different threads.
A.SomeList.Add(2.0);
or
A.SomeList.RemoveAt(0);
In other words, when is the lock released?
The Scoped Locking C++ idiom ensures that a lock is acquired when control enters a scope and the lock is released automatically when control leaves the scope. Also Known As. Synchronized Block, Object-Construction-is-Resource-Acquisition.
There is no way to lock in the c language. Operating systems might provide support for locking (without regard for the language), and libraries such as pthreads can take advantage of operating system services, however this is beside the language.
scoped_lock is for the simple case of wanting to lock some number of mutex objects in a deadlock-free way. Locking a single mutex is just a special case of locking multiple ones. The object is completely immobile, and it's very simple.
Lock: an object that can only be owned by a single thread at any given time (C++ class std::mutex ). Operations on a lock: lock : mark the lock as owned by the current thread; if some other thread already owns the lock then first wait until the lock is free.
There is no thread safety here.
The lock
is released as soon as the block it protects is finished, just before the property returns, so the calls to Add
ad RemoveAt
are not protected by the lock.
The lock you shown in the question isn't of much use.
To make list operations thread safe you need to implement your own Add/Remove/etc methods wrapping those of the list.
public void Add(double item)
{
lock(_list)
{
_list.Add(item);
}
}
Also, it's a good idea to hide the list itself from the consumers of your class, i.e. make the field private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With