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

  • SEARCH
  • Home
  • 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 8689075
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 12, 20262026-06-12T23:32:47+00:00 2026-06-12T23:32:47+00:00

I’m pretty new to threads and would like some insight. I’m trying to get

  • 0

I’m pretty new to threads and would like some insight. I’m trying to get the percentage each thread has completed for its calculation. Each thread will report its percentage to a different element of the same array. I have this working with pthread_join immediately after pthread_create and a separate thread for reading all the values of the array and printing the percentage but when I have all threads running after each other without waiting for the previous one to finish I get some weird behavior. This is how I’m accessing the shared (global) array.

//global
int *currentProgress;
//main
    currentProgress = malloc(sizeof(int)*threads);
    for(i=0; i<threads; i++)
        currentProgress[i] = 0;
//child threads
currentProgress[myId] = (int)percent; //myId is unique

//progress thread
for(i=0; i<threads; i++)
    progressTotal += currentProgress[i];
progressTotal /= threads;
printf("Percent: %d", progressTotal);

This is essentially the code I think is not being used correctly for multi-threads. When I print out the state of the shared array, I notice that as soon as another thread starts accessing the array (different element though), the previous element immediately goes to some random number… -2147483648 and when the latter element finishes the prior element continues like normal. Should I be using semaphores for this? I thought I could access different elements of an array at the same time and I thought reading them wasn’t an issue.

This is the entire code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <stdint.h>
#include <pthread.h>
#include <string.h>

#define STDIN 0


int counter = 0;
uint64_t *factors;
void *getFactors(void *arg);
void *deleteThreads(void *arg);
void *displayProgressThread(void *arg);
int *currentProgress;

struct data
{
    uint64_t num;
    uint64_t incrS;
    uint64_t incrF;
    int threads;
    int member;
} *args;

int main(int argc, char *argv[])
{

    if(argc < 3) {printf("not enough arguments"); exit(1);}

    int i;
    int threads = atoi(argv[2]);
    pthread_t thread_id[threads];
    pthread_t dThread;

    currentProgress = malloc(sizeof(int)*threads);
    for(i=0; i<threads; i++)
        currentProgress[i] = 0;

    args = (struct data*)malloc(sizeof(struct data));
    args->num = atoll(argv[1]);
    args->threads = threads;

    uint64_t increment = (uint64_t)sqrt((uint64_t)args->num)/threads;
    factors = (uint64_t*)malloc(sizeof(uint64_t)*increment*threads);

    pthread_create(&dThread, NULL, displayProgressThread, (void*)args);

    //for the id of each thread
    args->member = 0;
    for(i=0; i<threads; i++)
    {
            args->incrS = (i)*increment +1;
            args->incrF = (i+1)*increment +1;
            pthread_create(&thread_id[i], NULL, getFactors, (void*)args);
            usleep(5);
    }

    for(i=0; i<threads; i++)
    {
        pthread_join(thread_id[i], NULL);
    }
    sleep(1);
    printf("done\n");
    for (i=0; i<counter; i++)
        printf("\n%llu : %llu", factors[++i], factors[i]);
    return 0;
}

void *getFactors(void *arg)
{
    uint64_t  count;
    int myId;
    int tempCounter = 0, i;
    struct data *temp = (struct data *) arg;
    uint64_t number = temp->num;
    float total = temp->incrF - temp->incrS, percent;

    myId = temp->member++;

    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    for(count=temp->incrS; count<=temp->incrF; count++)
    {

        percent = (float)(count-temp->incrS)/total*100;
        currentProgress[myId] = (int)percent;

        if (number%count == 0)
         {
                factors[counter++] = count;
                factors[counter++] = number/count;
         }   
        usleep(1);
    }
    usleep(1);
    pthread_exit(NULL);
}

void *displayProgressThread(void *arg)
{
    struct data *temp = (struct data *) arg;
    int toDelete = 0;
    while(1)
    {
        int i;
        int progressTotal = 0;
        char *percent = malloc(sizeof(char)*20);
        for(i=0; i<toDelete; i++)
            printf("\b \b");

        for(i=0; i<temp->threads; i++){
            progressTotal += currentProgress[i];
        }

        progressTotal /= temp->threads;
        printf("|");
        for(i=0; i<50; i++)
            if(i<progressTotal/2)
                printf("#");
            else
                printf("_");
        printf("| ");
        sprintf(percent, "Percent: %d", progressTotal);
        printf("%s", percent);
        toDelete = 53 + strlen(percent);


usleep(1000);
    fflush(stdout);
    if(progressTotal >= 100)
        pthread_exit(NULL);
}

}

  • 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-12T23:32:48+00:00Added an answer on June 12, 2026 at 11:32 pm

    There are some non synchronized pieces of code that are accessed by the threads which cause this problem.

    One first place to be synchronized is:

       myId = temp->member++;
    

    But more importantly is that, the main thread is doing:

       args->incrS = (i)*increment +1;
       args->incrF = (i+1)*increment +1;
    

    while at the same time in the threads:

       for(count=temp->incrS; count<= temp->incrF; count++)
        {
    
            percent = (float)(count-temp->incrS)/total*100;
            currentProgress[myId] = (int)percent;
    
            if (number%count == 0)
             {
                    factors[counter++] = count;
                    factors[counter++] = number/count;
             }   
            usleep(1);
        }
    

    The unsynchronized accesses mentioned above affect the calculation of percent value which results in such abnormal happenings. You have to do synchronization in all these places in order to get the kind of behavior you would expect.

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

Sidebar

Related Questions

That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
For some reason, after submitting a string like this Jack’s Spindle from a text
I've got a string that has curly quotes in it. I'd like to replace
I am trying to render a haml file in a javascript response like so:
I would like to run a str_replace or preg_replace which looks for certain words
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I would like to count the length of a string with PHP. The string
I would like my Web page http://www.gmarks.org/math_in_e-mail.txt on my Apache 2.2.14 server to display
link Im having trouble converting the html entites into html characters, (&# 8217;) i

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.