0

Is it neccessary to create a placeholder lock object to for thread-safety (and correctness) or is it sufficient to lock on the resource itself (assuming no other code will need it).

locking a System.Random

private static readonly Random rnd = new Random();
public static int Rand(int min, int max) {
    lock(rnd) {
        return rnd.Next(min, max);
    }
}

using a separate placeholder/dummy lock object

private static readonly Random rnd = new Random();
private static readonly object rndLock = new object()
public static int Rand(int min, int max) {
    lock(rndLock) {
        return rnd.Next(min, max);
    }
}

this may seem trivial but i'm concerned with if the first code-block is susceptible to deadlock or other issues

xst
  • 2,536
  • 5
  • 29
  • 41
  • Creating separate object for lock is not necessary but strongly recommended. Reasons are covered in (duplicate) - [Why is lock(this) {…} bad](http://stackoverflow.com/questions/251391/why-is-lockthis-bad/251668#251668) . – Alexei Levenkov Sep 10 '14 at 23:10

1 Answers1

1

The reason we avoid locking the object itself, is to avoid the situation where a lock is taken inadvertently, if the "object itself" is publicly exposed. If you are only using the "object itself" inside a private class or method, there is no harm in using the method you propose.

Frank Hileman
  • 1,159
  • 9
  • 19