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 7611611
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T01:42:18+00:00 2026-05-31T01:42:18+00:00

I have written the follwing code to demonstrate race condition between 2 threads of

  • 0

I have written the follwing code to demonstrate race condition between 2 threads of a same process.

`

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

int c = 0;
void *fnC()
{
    int i;
    for(i=0;i<10;i++)
    {   
        c++;
        printf(" %d", c); 
    }   
}


int main()
{
    int rt1, rt2;
    pthread_t t1, t2; 
    /* Create two threads */
    if( (rt1=pthread_create( &t1, NULL, &fnC, NULL)) )
        printf("Thread creation failed: %d\n", rt1);
    if( (rt2=pthread_create( &t2, NULL, &fnC, NULL)) )
        printf("Thread creation failed: %d\n", rt2);
    /* Wait for both threads to finish */
    pthread_join( t1, NULL);
    pthread_join( t2, NULL);
    printf ("\n");
    return 0;

}

`

I ran this program, and expected a race condition to occur between the 2 threads (but, I understand that the probablity for race condition is very less, as the thread main function very small).
I ran this 50000 times. The following was the output,

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 - 49657 times (no race condition)
1 3 4 5 6 7 8 9 10 11 2 12 13 14 15 16 17 18 19 20 - 244 times (race condition occurs)
2 3 4 5 6 7 8 9 10 11 1 12 13 14 15 16 17 18 19 20 - 99 times (race condition occurs)

The question is,
When race condition occurs as in output 2, thread 1 prints 1 and is swapped out of the processor and thread 2 comes in. It starts working and after thread 2 prints 11, it gets swapped out, thread 1 comes in. It has to print 12, but rather it is printing 2 (actually 2 should be missing). I can’t figure out how. Please help me understand what happens here.

  • 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-31T01:42:19+00:00Added an answer on May 31, 2026 at 1:42 am

    You’re thinking in a C mindset, but if you want to think about race conditions you have to think on a lower level.

    In a debugger, you normally set a breakpoint on a single line of code, and you can watch each line of code being executed by stepping through your program. But that’s not how the machine works, the machine may execute several instructions for each line of code and threads can be interrupted anywhere.

    Let’s look at this one line.

    printf(" %d", c);
    

    In machine code, it looks something like this:

    load pointer to " %d" string constant
    load value of c global
    # <- thread might get interrupted here
    call printf
    

    So the behavior is not unexpected. You have to load the value of c before you can call printf, so if the thread is interrupted there is always a chance that c is stale by the time printf does anything. Unless you do something to stop it.

    Fixing the race condition:

    pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    
    int c = 0;
    void *func(void *param)
    {
        int i;
        for (i=0; i<10; i++) {
            pthread_mutex_lock(&mutex);
            c++;
            printf(" %d", c);
            pthread_mutex_unlock(&mutex);
        }
        return NULL;
    }
    

    What does volatile do?

    The code in the question can translate to assembly code like the following:

    load the current value of c
    add 1 to it
    store it in c
    call printf
    

    It doesn’t have to reload c after it increments it, since the C compiler is allowed to assume that nobody else (no other thread or device) changes memory except the current thread.

    If you use volatile, the compiler will be strict about keeping every load and store operation, and the assembly will look something like this:

    load the current value of c
    add 1 to it
    store it in c
    # compiler is not allowed to cache c
    load the current value of c
    call printf
    

    This doesn’t help. In fact, volatile almost never helps. Most C programmers don’t understand volatile, and it’s almost useless for writing multithreaded code. It’s useful for writing signal handlers, memory-mapped IO (device drivers / embedded programming), and it’s useful for correctly using setjmp/longjmp.

    Footnote:

    The compiler can’t cache the value of c across a call to printf, because as far as the compiler knows, printf can change c (c is a global variable, after all). Someday, the compiler may get more sophisticated and it may know that printf doesn’t change c, so the program may break even more severly.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have written the following code in MATLAB to process large images of the
I have written a following code to get just the file name without extension
I have written the following code choice /m Do you want to add another
I have written the following code. But it is removing only &nbsp; not <br>
i have written the following code: As you can see there is a for
I have written the following IronPython code: import clr clr.AddReference(System.Drawing) from System import *
I have written my code in following way in cocos2d. id actionTo = [CCFadeOut
In physics library written in C# I have the following code: (in ContactManager.cs) public
Summary I have written a process monitor command-line application that takes as parameters: The
I have written following code to set the status of the image button to

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.