Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lock scope in C#: is returned object still "locked"?

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?

like image 592
Pierre-Antoine Avatar asked Apr 01 '12 17:04

Pierre-Antoine


People also ask

What is a scope lock?

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.

What is lock in C language?

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.

Is scoped_lock movable?

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.

What is a lock in C++?

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.


2 Answers

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.

like image 83
Oded Avatar answered Oct 18 '22 23:10

Oded


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.

like image 42
Gebb Avatar answered Oct 18 '22 23:10

Gebb