Working on 14.2.4 Local vs Shared State

Jason Zhu 2021-07-27 16:24:46 +10:00
parent c19bce052f
commit 19ea7f2052

@ -154,6 +154,47 @@ Pro & Con of Blocking and Spinning:
### 14.2.4 Local vs Shared State
#### Local State
CLR assign each threas its own memory stack so local variables are kept separate
```csharp
void Go()
{
// Declare and use a local variable 'cycles'
for (int cycles = 0; cycles < 5; cycles++ )
{
Console.Write('?');
}
}
// Create a new thread and call Go() on it
new Thread(Go).Start();
// Call Go() on main thread
Go();
```
#### Shared State
Mutliple threads share data if all threads have a common reference to the same object or variable:
e.g. Both threads share a boolean and that boolean is changed.
```csharp
bool _done = false;
new Thread(Go).Start();
Go();
void Go()
{
if (!_done) { _done = true; Console.WriteLine("Done"); } // Executed only once, as it's _done is changed during one of threads' execution
}
```
### 14.2.5 Locking and Thread Safety
### 14.2.6 Passing Data to a Thread