Provided that only conditions and increment / decrement are used. I want to speed up the work of a multithreaded application. Interested in how unsafe it is in terms of an error.

  • one
    If data is used in different streams, then it is necessary to synchronize. And it can work for a very long time without synchronization, but when an error occurs, then the chances of finding it will be almost zero. - alexlz
  • And there are ways that work faster lock? - Jakeroid
  • one
    No, lock is the fastest way to sync proof. - Specter
  • Well, in this proof about the stagnation of Interlocked (see answer @ Vasily), nothing is said. - alexlz pm

2 answers 2

If the treatment is read-only or access to the data is atomic, then it is safe. Otherwise, there is the possibility of poorly predictable racing.

In the case of increment and decrement, it is sufficient to use the class System.Threading.Interlocked , which ensures that the operations are atomic. In this case, no additional synchronization is required.

  • Plus set, but. If the work is organized in such a way that right after the increment / decrement the flow checks the value (or vice versa - the check and the result, immediately, the modification), then this option, I think, will not work. - alexlz

As an alternative to software synchronization at the client level, you can try to apply the transaction isolation mechanism provided at the server level. For example, if it is MS SQL Server, then it is enough to send a server ( dock ) to the server before starting the request:


After that, all requests will automatically become synchronized. I do not know whether this will be faster - this is a question. You can also play around with the isolation level of transactions - it can help.

  • My program does not communicate with the database. - Jakeroid
  • Oops ... - I was thinking about the database ... - Barmaley
  • I wonder how many orders of speed these options differ? Three, four, more? - alexlz