Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6530113
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T09:43:00+00:00 2026-05-25T09:43:00+00:00

Possible Duplicate: Threads synchronization. How exactly lock makes access to memory 'correct'? This question

  • 0

Possible Duplicate:
Threads synchronization. How exactly lock makes access to memory 'correct'?

This question is inspired by this one.

We got a following test class

class Test
{
    private static object ms_Lock=new object();
    private static int ms_Sum = 0;

    public static void Main ()
    {
        Parallel.Invoke(HalfJob, HalfJob);
        Console.WriteLine(ms_Sum);
        Console.ReadLine();
    }

    private static void HalfJob()
    {
        for (int i = 0; i < 50000000; i++) {
            lock(ms_Lock) { }// empty lock

            ms_Sum += 1;
        }
    }
}

Actual result is very close to expected value 100 000 000 (50 000 000 x 2, since 2 loops are running at the same time), with around 600 – 200 difference (mistake is approx 0.0004% on my machine which is very low). No other way of synchronization can provide such way of approximation (its either a much bigger mistake % or its 100% correct)

We currently understand that such level of preciseness is because of program runs in the following way:

enter image description here

Time is running left to right, and 2 threads are represented by two rows.

where

  • black box represents process of acquiring, holding and releasing the

  • lock plus represents addition operation ( schema represents scale on
    my PC, lock takes approximated 20 times longer than add)

  • white box represents period that consists of try to acquire lock,
    and further awaiting for it to become available

Also lock provides full memory fence.

So the question now is: if above schema represents what is going on, what is the cause of such big error (now its big cause schema looks like very strong syncrhonization schema)? We could understand difference between 1-10 on boundaries, but its clearly no the only reason of error? We cannot see when writes to ms_Sum can happen at the same time, to cause the error.

EDIT: many people like to jump to quick conclusions. I know what synchronization is, and that above construct is not a real or close to good way to synchronize threads if we need correct result. Have some faith in poster or maybe read linked answer first. I don’t need a way to synchronize 2 threads to perform additions in parallel, I am exploring this extravagant and yet efficient , compared to any possible and approximate alternative, synchronization construct (it does synchronize to some extent so its not meaningless like suggested)

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T09:43:01+00:00Added an answer on May 25, 2026 at 9:43 am

    This is a very tight loop with not much going on inside it, so ms_Sum += 1 has a reasonable chance of being executed in “just the wrong moment” by the parallel threads.

    Why would you ever write a code like this in practice?

    Why not:

    lock(ms_Lock) { 
        ms_Sum += 1;
    }
    

    or just:

    Interlocked.Increment(ms_Sum);
    

    ?

    — EDIT —

    Some comments on why would you see the error despite memory barrier aspect of the lock… Imagine the following scenario:

    • Thread A enters the lock, leaves the lock and then is pre-empted by the OS scheduler.
    • Thread B enters and leaves the lock (possibly once, possibly more than once, possibly millions of times).
    • At that point the thread A is scheduled again.
    • Both A and B hit the ms_Sum += 1 at the same time, resulting in some increments being lost (because increment = load + add + store).
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Possible Duplicate: .NET Controls: Why aren’t all calls thread-safe? This question is not about
Possible Duplicate: Why is lock(this) {…} bad? In C# to make a critical region
Possible Duplicate: The calling thread cannot access this object because a different thread owns
Possible Duplicate: Could you explain STA and MTA? All ThreadPool threads are in the
Possible Duplicate: Return value from thread I want to get the free memory of
Possible duplicate question: Is there a way to indefinitely pause a thread? In my
Possible Duplicate: NAnt or MSBuild, which one to choose and when? What is the
Possible Duplicate: How do I calculate someone's age in C#? Maybe this could be
Possible Duplicate: C# Spawn Multiple Threads for work then wait until all finished I
Possible Duplicate: Locking main() thread Below you'll find my code, Main calls two threads,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.