Note that there are some explanatory texts on larger screens.

plurals
  1. POIs this how to write a Thread-Safe IComparable?
    primarykey
    data
    text
    <p>I have a simple class and I want to make it thread-safe. The class needs to implement IComparer. I know that implementing the <code>int CompareTo(T other)</code> in a thread-safe way is not straight-forward. It's easy to allow a deadlock if I don't lock in the right way. I have three questions:</p> <ol> <li>Is this code thread-safe? If not, how can I fix it?</li> <li>Can this code be any shorter? It seems like a lot of code for a simple subtraction.</li> <li>Should I even bother making <code>int CompareTo(T other)</code> thread-safe? Should I instead require that the caller (usually sorting) lock all of the relevant BObjects?</li> </ol> <p>Here's my code:</p> <pre><code>public class BObject : IComparable&lt;BObject&gt; { //Each BObject has a unique object id private static int _bObjectId = 0; private static int GetNextId() { return System.Threading.Interlocked.Increment(ref BObject._bObjectId); } private object _locker = new object(); private readonly int _id = BObject.GetNextId(); //Some variable private int _sales; public int Sales { get { lock (this._locker) return this._sales; } set { lock (this._locker) this._sales = value; } } public int CompareTo(BObject other) { int result; //Can I simply do "if (this._id == other._id)" if (object.ReferenceEquals(this, other)) result = 0; else { //get the BObject with the lower id BObject lower = this._id &lt; other._id ? this : other; //get the BObject with the higher id BObject higher = this._id &gt; other._id ? this : other; //lock the BObject with the lower id first lock (lower._locker) { //lock the BObject with the higher id last lock (higher._locker) { //put object with lower Sales first result = this.Sales - other.Sales; } } } return result; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload