Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
6.1 Parallelism: race conditions
//6.1 Parallelism: race conditions using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace Rextester { public class Program { public static void Main(string[] args) { //Threads introduce a lot of new interesting bug types. One of them is called race condition. //These are hard to catch and even hard to produce intentionally! int total_threads = 0; for(int i=0; i<100; i++) { ThreadPool.QueueUserWorkItem(f => { if(total_threads == 50) Console.WriteLine("50!"); total_threads++; }); } Thread.Sleep(5000); //Anyway this code has race condition and sometimes (maybe very rarely) it will print more than just one line "50!" or won't print anything at all. //It is because variable total_threads is accesed from many threads "simultaneously". And this could happen: //Thread A checks for value: it's 49 and goes to next command (total_threads++;) //But then Thread B kicks in and checks for value and it is still 49, so it goes to next command (total_threads++;) //Thread A kicks in back and continues where it was interrupted and executes total_threads++; making value equal to 50 //Thread B kicks in back and continues where it was interrupted and executes total_threads++; making value equal to 51 //And in this case no thread will have total_threads == 50 so nothing will be printed. //The main point is that threads can be interrupted at any point and resumed later and anything in other threads can happen in between //Even this instruction - total_threads++; can be interrupted in the midle, because it actually consists of several assembly instructions: //mov $ptr, eax - move memory value to eax register //inc eax - increment by one //mov eax, $ptr - write back to memory //and interruption can happen after any of these instructions //How to avoid problems like this one? Locks! } } }
run
|
edit
|
history
|
help
0
K
Big numbers
https://rextester.com/ZZVYV85848
test array with c#
7.2 Creating async methods the old way
IEnumerable<T> generic interface implementation
Rotation String
Delegate In C#
Volatile madness
lasses, properties, methods, ling begining