Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Consider the following two alternatives of getting the higher 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 about a context where the currentPrice variable could be edited by other threads.

In the first case... could price obtain a value lower than 100?

I'm thinking about the following:

if (currentPrice > 100) {
    //currentPrice is edited here.
    price = currentPrice;
}
like image 846
Oscar Mederos Avatar asked Oct 13 '12 06:10

Oscar Mederos


2 Answers

It is not threadsafe.

?: is just shortcut for normal if, so your if sample is equivalent to ? one - you can get price lower than 100 if there is no locking outside this code.

like image 147
Alexei Levenkov Avatar answered Sep 30 '22 12:09

Alexei Levenkov


Not a specialist in C#, but even var++ is not thread save, since may translated to from reading into/writing from register in assembly.

Ternary operator is far more complicated. It has 3 parts, while each part can be endlessly big (e.g. call to some function). Therefore, it's pretty easy to conclude that ternary operator is not thread safe.

like image 29
dimba Avatar answered Sep 30 '22 12:09

dimba