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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T18:00:08+00:00 2026-06-06T18:00:08+00:00

I am trying to use pthread mutex variables and barrier to synchronize the output

  • 0

I am trying to use pthread mutex variables and barrier to synchronize the output of my program, but it is not working the way I want it to. Each thread is seeing its final value every 20 values (coming from the for loop) which is alright but I’m trying to make them all get to the same final value (if using 5 threads, all of them should see 100 as final value, with 4 threads, 80, etc)

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

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;

int SharedVariable =0;
void *SimpleThread(void *args)
{
    int num,val,rc;
    int which =(int)args;
    rc = pthread_mutex_lock(&mutex1);
    for(num=0; num<20; num++){
#ifdef PTHREAD_SYNC
        if(random() > RAND_MAX / 2)
            usleep(10);
#endif
        //pthread_mutex_lock(&mutex1);
        val = SharedVariable;
        printf("*** thread %d sees value %d\n", which, val);
        //pthread_mutex_lock(&mutex1);
        SharedVariable = val+1;
        pthread_mutex_unlock(&mutex1);
    }   
    val=SharedVariable;

    printf("Thread %d sees final value %d\n", which, val);
    //pthread_mutex_destroy(&mutex1);
    //pthread_exit((void*) 0);
    //pthread_mutex_unlock(&mutex1);

}

int main (int argc, char *argv[])
{
   if(atoi(argv[1]) > 0){        
   int num_threads = atoi(argv[1]);  
   //pthread_mutex_init(&mutex1, NULL);
   pthread_t threads[num_threads];
   int rc;
   long t;
   rc = pthread_mutex_lock(&mutex1);
   for(t=0; t< num_threads; t++){
      printf("In main: creating thread %ld\n", t);
      rc = pthread_create(&threads[t], NULL, SimpleThread, (void* )t);
      if (rc){
         printf("ERROR; return code from pthread_create() is %d\n", rc);
         exit(-1);
      }

    //pthread_join(thread1);

   }
    rc= pthread_mutex_unlock(&mutex1);
}
   else{
      printf("ERROR: The parameter should be a valid positive number.");
      exit(-1);
  }

   pthread_mutex_destroy(&mutex1);
   pthread_exit(NULL);
}

Any suggestions or help is greatly appreciated!
Thanks in advanced!

  • 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-06T18:00:11+00:00Added an answer on June 6, 2026 at 6:00 pm

    You need to use a barrier (pthread_barrier_wait()) before checking for the final value – this ensures that no thread will proceed until all threads have reached the barrier.

    In addition, you should be calling pthread_join() to wait for the threads to finish, and you only need to hold the mutex around the increment:

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
    pthread_barrier_t barrier1;
    
    int SharedVariable = 0;
    
    void *SimpleThread(void *args)
    {
        int num,val;
        int which = (int)args;
    
        for(num = 0; num < 20; num++) {
    #ifdef PTHREAD_SYNC
            if(random() > RAND_MAX / 2)
                usleep(10);
    #endif
            pthread_mutex_lock(&mutex1);
            val = SharedVariable;
            printf("*** thread %d sees value %d\n", which, val);
            SharedVariable = val + 1;
            pthread_mutex_unlock(&mutex1);
        }
    
        pthread_barrier_wait(&barrier1);
    
        val = SharedVariable;
        printf("Thread %d sees final value %d\n", which, val);
        return 0;
    }
    
    int main (int argc, char *argv[])
    {
        int num_threads = argc > 1 ? atoi(argv[1]) : 0;
    
        if (num_threads > 0) {
            pthread_t threads[num_threads];
            int rc;
            long t;
    
            rc = pthread_barrier_init(&barrier1, NULL, num_threads);
    
            if (rc) {
                fprintf(stderr, "pthread_barrier_init: %s\n", strerror(rc));
                exit(1);
            }
    
            for (t = 0; t < num_threads; t++) {
                printf("In main: creating thread %ld\n", t);
                rc = pthread_create(&threads[t], NULL, SimpleThread, (void* )t);
                if (rc) {
                    printf("ERROR; return code from pthread_create() is %d\n", rc);
                    exit(-1);
                }
            }
    
            for (t = 0; t < num_threads; t++) {
                pthread_join(threads[t], NULL);
            }
        }
        else {
            printf("ERROR: The parameter should be a valid positive number.\n");
            exit(-1);
        }
    
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to produce random numbers for each thread to use, but all
I'm trying to write a simple thread pool program in pthread. However, it seems
I am trying use an if statement and TWO .addClass background-color variables based on
I was trying use svn to find a checkin using svn log, but it
I am trying use Thread but i have some problem (I am beginner at
I am working on a project and trying to use pthread_cond_wait() and pthread_cond_signal() to
I am trying to compare the performance of boost::atomic and pthread mutex on Linux:
I was trying use a set of filter functions to run the appropriate routine,
I'm trying use self-signed certificate (c#): X509Certificate2 cert = new X509Certificate2( Server.MapPath(~/App_Data/myhost.pfx), pass); on
I'm trying use mod_rewrite to rewrite URLs from the following: http://www.site.com/one-two-file.php to http://www.site.com/one/two/file.php The

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.