Is the ternary operator (? :) a thread safe in C #?

Consider the following two options for getting a larger number between currentPrice and 100 ...

 int price = currentPrice > 100 ? currentPrice : 100 int price = Math.Max(currentPrice, 100) 

I raised this question because I was thinking of a context in which the currentPrice variable could be edited by other threads.

In the first case ... can price get a value below 100 ?

I think of the following:

 if (currentPrice > 100) { //currentPrice is edited here. price = currentPrice; } 
+7
source share
4 answers

It is not thread safe.

?: - is it just a shortcut for regular if , so is your if pattern equivalent ? one - you can get a price below 100 if there is no blocking outside this code.

+8
source

In theory, currentPrice is read twice. Once for comparison, once for appointment.

In practice, the compiler can cache variable access. I don't know about C #, but in C ++ on x86:

 MOV AX, [currentPrice] MOV BX, 100 ;cache the immediate CMP AX, BX JLE $1 ;if(currentPrice > 100){ MOV AX, BX $1: ;} MOV [BP+price], AX ;price is on the stack. 

The same loading optimization is once performed in Java bytecode unless currentPrice is declared mutable.

So, theoretically, this can happen. In practice, on most platforms this will not happen, but you cannot count on it.

+3
source

Not an expert in C #, but even var ++ does not support a stream, since it can be translated to read / write from a register in an assembly.

The ternary operator is much more complicated. It has 3 parts, while each part can be infinitely large (for example, call some function). Therefore, it is fairly easy to conclude that the ternary operator is not thread safe.

+3
source

As indicated by others, it can be cached, but the language does not require it.

You can use Interlocked.CompareExchange if you need thread-safe destinations without blocking. But, given the example, I would go for a larger blocking strategy.

+1
source

All Articles