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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T06:36:23+00:00 2026-06-16T06:36:23+00:00

I wrote this piece of code #include <stdio.h> /* Input/Output */ #include <stdlib.h> /*

  • 0

I wrote this piece of code

#include <stdio.h>      /* Input/Output */
#include <stdlib.h>     /* General Utilities */
#include <pthread.h>    /* POSIX Threads */
unsigned int cnt=0;  /*Count  variable%*/
const int NITERS=1000;
void count()
{
    int i=0;
    for(i=0; i<NITERS; i++)
    {
        cnt++;
    }
    pthread_exit(0);
}
int main()
{
    pthread_t tid1,tid2;
     /* create threads 1 and 2 */  
    pthread_create(&tid1,NULL,count,NULL);
    pthread_create(&tid2,NULL,count,NULL);
    /* Main block now waits for both threads to terminate, before it exits
       If main block exits, both threads exit, even if the threads have not
       finished their work */ 
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    if(cnt!=(unsigned)NITERS*2)
    {
        printf("BOOM! cnt=%d, it should be %d\n",cnt,NITERS*2);
    }
    else
    {
        printf("OK! cnt=%d\n",cnt);
    }
    exit(0);
}

and it exhibits this result.
Result to the code

Some time it get cnt to be 2000 but most of the time it is giving the result less than 2000. Can you please explain why is it happening or what is the reason behind this? How to fix it. Your answers and reasons will be sure of great help.

  • 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-06-16T06:36:24+00:00Added an answer on June 16, 2026 at 6:36 am

    unsigned int cnt=0; is share-able among the threads and operation ++ is not atomically increase cnt. Two thread may read same values of cnt and increase, and overwrites cnt. You need to apply some concurrency control mechanism like semaphore, or mutex.


    If you would disassemble code using following command (suppose code name is thread1.c)

    ~$ gcc thread.c -lpthread -S  
    

    The output assembly code name is thread1.s.

    your wil find cnt++ is more then one instruction in low level in your code:

        movl    $0, -12(%ebp)
        jmp .L2
    .L3:
        movl    cnt, %eax
        addl    $1, %eax
        movl    %eax, cnt
        addl    $1, -12(%ebp)
    .L2:
        movl    NITERS, %eax
    

    (1) cnt fist move to %eax
    (2) then add one to %exc
    (3) move %eax into cnt back

    And due to thread context switching in between this line, same value of cnt is read by more than one threads. hence cnt++ is not atomic.

    Note: Global variable are thread shareable like cnt, and local variable like i that you declared in count() is thread specific.


    I modified your code and imposed concurrency control using semaphore, now it would work fine.

    Only modified code shown

    #include <pthread.h>    /* POSIX Threads */
    #include <semaphore.h>
    unsigned int cnt=0;  /*Count  variable%*/
    const int NITERS=1000;
    
    sem_t mysem;
    
    void count()
    {
        int i=0;
        for(i=0; i<NITERS; i++)
        {
            sem_wait(&mysem);
            cnt++;
            sem_post(&mysem);
        }
        pthread_exit(0);
    }
    int main()
    {
        if ( sem_init(&mysem,0,1) ) {
         perror("init");
        }
        // rest of your code 
    } 
    

    This will work good! some examples:

    nms@NMS:~$ ./thread 
    OK! cnt=2000
    nms@NMS:~$ ./thread 
    OK! cnt=2000
    nms@NMS:~$ ./thread 
    OK! cnt=2000
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wrote this small piece of code to test something: #include <stdio.h> int main()
I wrote this simple piece of code to dynamically allocate a 4-dimensional array: #include
I wrote this piece of code that is supposed to redirect something written on
I've wrote this simple piece of code. And I have a slight problem with
I have a program I wrote in Windows with this piece of code that
I wrote this piece of code that lists all JPG files in the current
This is a simple piece of code which i wrote to check whether it
I wrote this small piece of code in C to test memcmp() strncmp() strcmp()
[related to this question ] I wrote this piece of code to understand how
I wrote this piece of code in order to display the current date +

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.