Back
Close

Computing with Data

elgeish
33.2K views

Ineffectual Synchronization - Part III

Another example of ineffectual synchronization, that's not applicable in Java but can happen in C#, is demonstrated below:

using System;
using System.Threading;
class Program
{
static int sum = 0;
static void DoWork()
{
lock ((object) 0)
{
for (int i = 0; i < 10000; i++)
{
++sum;
}
}
}
static void Main()
{
for (int i = 0; i < 4; i++)
{
new Thread(DoWork).Start();
}
Thread.Sleep(1000); // ad-hoc wait till threads finish
Console.WriteLine("C# sum: " + sum);
}
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants