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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 30, 20262026-05-30T01:57:35+00:00 2026-05-30T01:57:35+00:00

EDIT 1: FILE *fp; pthread_mutex_t demoMutex; unsigned short globalThreadIndex = 0; struct serverInfo {

  • 0

EDIT 1:

FILE            *fp;
pthread_mutex_t demoMutex;
unsigned short globalThreadIndex = 0;

struct serverInfo
{
    unsigned int                 serverId;
    pthread_t                        threadId;
    std :: vector <pthread_t> queue;
};

std :: vector <serverInfo> serverInfoVector;


void * printHello (void* threadId)
{
    pthread_t *my_tid = (pthread_t *)&threadId;
    printf ("\nIn `printHello ()`: thread id %ld\n", pthread_self ());

    ***pthread_mutex_lock (&demoMutex);***

    unsigned int i = 0;
    char               found = false;

    if (serverInfoVector.size () > 0)
    {
        // The following code should be executed when and only when the vector isn't empty.
        ***pthread_cond_wait (&demoConditionVar, &demoMutex);***

        while ((i <= serverInfoVector.size ()) && (found == false))
        {
            if (*my_tid == serverInfoVector [i].threadId)
            {
                found = true;
                break;
            }
            else
                i++;
        }

        if (found == true)
        {
            pthread_t            writeToFile = pthread_self ();
            unsigned short iterate;
            for (iterate = 0; iterate < 10000; iterate++)
            {
                fprintf (fp, " %d %d",  iterate,         4);
                fprintf (fp, " %lu %lu", writeToFile, sizeof (pthread_t));

                if (!serverInfoVector [i].queue.empty ())
                {
                    fprintf (fp, " %c %u", 'A', 1);
                    fprintf (fp, " %lu %lu", serverInfoVector [i].queue.front (), sizeof (pthread_t));
                    serverInfoVector [i].queue.pop_back ();
                }
                fprintf (fp, "\n %lu %u", writeToFile, 1);
            }
        }
        ***pthread_mutex_unlock (&demoMutex);***
        }
    ***pthread_exit (NULL);***
}

void checkServerExists (unsigned int serverNumber, std :: string message)
{
    unsigned int i         = 0;
    char               found = false;

    if (serverInfoVector.size () > 0)
    {
        while ((i <= serverInfoVector.size ()) && (found == false))
        {
            if (serverNumber == serverInfoVector [i].threadId)
            {
                found = true;
                break;
            }
            else
                i++;
        }
    }

    if (found == false)
    {
        pthread_t newThread [2];

        int           returnValue;
        if ((returnValue = pthread_create (&newThread [globalThreadIndex], NULL, printHello, (void*) &newThread [globalThreadIndex])) != 0)
        {
          printf ("\nerror: pthread_create failed with error number %d", returnValue);
        }
        printf ("\nIn checkServerExists ()`: thread id %ld\n", newThread [globalThreadIndex]);

        serverInfo obj;
        obj.serverId  = serverNumber;
        obj.threadId = newThread [globalThreadIndex];
        obj.queue.push_back (newThread [globalThreadIndex]);
        serverInfoVector.push_back (obj);

        // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.
        ***pthread_mutex_lock (&demoMutex)***; 
        // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.
        if (serverInfoVector.size () > 0)
            ***pthread_cond_signal (&demoConditionVar);***

        ***pthread_mutex_unlock(&demoMutex);*** 

        pthread_join (newThread [globalThreadIndex], NULL);
    }
    else
    {
    }
}


int main ()
{
    fp = fopen ("xyz", "w");
    ***pthread_mutex_init (&demoMutex, NULL);
    pthread_cond_t demoConditionVar = PTHREAD_COND_INITIALIZER;***

    checkServerExists (1, "anisha");
    globalThreadIndex++;
    checkServerExists (2, "anisha");

    return 0;
}

This code is improved, the problem is still there (the program hangs, second thread doesn’t get shown up).

checkServerExists function (in the current case) causes a new thread to be created, and stored in the array newThread.

checkServerExists function launches a new thread,

When the thread gets created it will immediately call its function printHello and get blocked on the condition variable.

checkServerExists function then inputs the value in the global structure’s queue, sets the signal for the thread to waken up.

Now, what’s the point that I am missing?

EDIT 2:

FILE            *fp;
pthread_mutex_t demoMutex;
unsigned short globalThreadIndex = 0;

struct serverInfo
{
    unsigned int                 serverId;
    pthread_t                        threadId;
    std :: vector <pthread_t> queue;
};

std :: vector <serverInfo> serverInfoVector;


void * printHello (void* threadId)
{
    pthread_t *my_tid = (pthread_t *)&threadId;
    printf ("\nIn `printHello ()`: thread id %ld\n", pthread_self ());

    ***pthread_mutex_lock (&demoMutex);***

    unsigned int i = 0;
    char               found = false;

    if (serverInfoVector.size () > 0)
    {
        // The following code should be executed when and only when the vector isn't empty.
        ***pthread_cond_wait (&demoConditionVar, &demoMutex);***

        while ((i <= serverInfoVector.size ()) && (found == false))
        {
            if (*my_tid == serverInfoVector [i].threadId)
            {
                found = true;
                break;
            }
            else
                i++;
        }

        if (found == true)
        {
            pthread_t            writeToFile = pthread_self ();
            unsigned short iterate;
            for (iterate = 0; iterate < 10000; iterate++)
            {
                fprintf (fp, " %d %d",  iterate,         4);
                fprintf (fp, " %lu %lu", writeToFile, sizeof (pthread_t));

                if (!serverInfoVector [i].queue.empty ())
                {
                    fprintf (fp, " %c %u", 'A', 1);
                    fprintf (fp, " %lu %lu", serverInfoVector [i].queue.front (), sizeof (pthread_t));
                    serverInfoVector [i].queue.pop_back ();
                }
                fprintf (fp, "\n %lu %u", writeToFile, 1);
            }
        }
        ***pthread_mutex_unlock (&demoMutex);***
        }
    ***pthread_exit (NULL);***
}

void checkServerExists (unsigned int serverNumber, std :: string message)
{
    unsigned int i         = 0;
    char               found = false;

    ***pthread_mutex_lock (&demoMutex);*** 

    if (serverInfoVector.size () > 0)
    {
        while ((i <= serverInfoVector.size ()) && (found == false))
        {
            if (serverNumber == serverInfoVector [i].threadId)
            {
                found = true;
                break;
            }
            else
                i++;
        }
    }

    if (found == false)
    {
        pthread_t newThread [2];

        int           returnValue;
        if ((returnValue = pthread_create (&newThread [globalThreadIndex], NULL, printHello, (void*) &newThread [globalThreadIndex])) != 0)
        {
              printf ("\nerror: pthread_create failed with error number %d", returnValue);
        }
        printf ("\nIn checkServerExists ()`: thread id %ld\n", newThread [globalThreadIndex]);

        serverInfo obj;
        obj.serverId  = serverNumber;
        obj.threadId = newThread [globalThreadIndex];
        obj.queue.push_back (newThread [globalThreadIndex]);
        serverInfoVector.push_back (obj);

        // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.

        // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.
        if (serverInfoVector.size () > 0)
            ***pthread_cond_signal (&demoConditionVar);***


        pthread_join (newThread [globalThreadIndex], NULL);
    }
    else
    {
    }
        ***pthread_mutex_unlock(&demoMutex);*** 
}


int main ()
{
    fp = fopen ("xyz", "w");
    ***pthread_mutex_init (&demoMutex, NULL);
    pthread_cond_t demoConditionVar = PTHREAD_COND_INITIALIZER;***

    checkServerExists (1, "anisha");
    globalThreadIndex++;
    checkServerExists (2, "anisha");

    return 0;
}

In this edit, I have placed the lock on the top of checkServerExists function (this function deals with the global structure serverInfoVector)

Still hanging. :doh:

  • 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-30T01:57:36+00:00Added an answer on May 30, 2026 at 1:57 am

    This code is broken.

    Firstly, you are modifying variables inside checkServerExists without locking the mutex. This is undefined behaviour.

    If you fix that, then you are also not signalling your condition variable outside the printHello function. Consequently, once the thread has blocked in the pthread_cond_wait call, it will only wake due to spurious wakes, and when another printHello thread signals it. You should call pthread_cond_signal at the point where you set the condition flag, rather than in printHello.

    A condition variable is just a notification mechanism. You need to associate a predicate with it, which is the condition being waited for (in your case, condition!=0). You must ensure that the variables accessed when setting and testing the condition are protected by a mutex, and that this mutex is the one passed to pthread_cond_wait in order to avoid potential race conditions. When you set the variables to indicate that the sleeping thread should wake, then you call pthread_cond_signal.

    I’ve modified your code slightly to make it work. In particular, I’ve put the loop round the pthread_cond_wait call, and unlocked the mutex before calling pthread_join so that the printHello thread can acquire the mutex and proceed. You should never hold a mutex lock across a thread join. This code could still be improved greatly — amongst other things, it is not exception safe.

    #include <pthread.h>
    #include <stdio.h>
    #include <vector>
    #include <string>
    FILE            *fp;
    pthread_mutex_t demoMutex;
    pthread_cond_t demoConditionVar;
    
    unsigned short globalThreadIndex = 0;
    
    struct serverInfo
    {
        unsigned int                 serverId;
        pthread_t                        threadId;
        std :: vector <pthread_t> queue;
    };
    
    std :: vector <serverInfo> serverInfoVector;
    
    void * printHello (void* threadId)
    {
        pthread_t *my_tid = (pthread_t *)threadId;
        printf ("\nIn `printHello ()`: thread id %ld\n", pthread_self ());
    
        pthread_mutex_lock (&demoMutex);
    
        unsigned int i = 0;
        bool found = false;
    
        while (serverInfoVector.empty())
            pthread_cond_wait (&demoConditionVar, &demoMutex);
    
        while ((i < serverInfoVector.size ()) && !found)
        {
            if (*my_tid == serverInfoVector [i].threadId)
            {
                found = true;
                break;
            }
            else
                i++;
        }
    
    
        if (found)
        {
            pthread_t            writeToFile = pthread_self ();
            unsigned short iterate;
            for (iterate = 0; iterate < 10000; iterate++)
            {
                fprintf (fp, " %d %d",  iterate,         4);
                fprintf (fp, " %lu %lu", writeToFile, sizeof (pthread_t));
    
                if (!serverInfoVector [i].queue.empty ())
                {
                    fprintf (fp, " %c %u", 'A', 1);
                    fprintf (fp, " %lu %lu", serverInfoVector [i].queue.front (), sizeof (pthread_t));
                    serverInfoVector [i].queue.pop_back ();
                }
                fprintf (fp, "\n %lu %u", writeToFile, 1);
            }
        }
        pthread_mutex_unlock (&demoMutex);
        pthread_exit (NULL);
    }
    
    void checkServerExists (unsigned int serverNumber, std :: string message)
    {
        unsigned int i         = 0;
        bool found = false;
    
        pthread_mutex_lock (&demoMutex);
    
        if (serverInfoVector.size () > 0)
        {
            while ((i <= serverInfoVector.size ()) && (found == false))
            {
                if (serverNumber == serverInfoVector [i].threadId)
                {
                    found = true;
                    break;
                }
                else
                    i++;
            }
        }
    
        if (!found)
        {
            pthread_t newThread [2];
    
            int           returnValue;
            if ((returnValue = pthread_create (&newThread [globalThreadIndex], NULL, printHello, (void*) &newThread [globalThreadIndex])) != 0)
            {
                printf ("\nerror: pthread_create failed with error number %d", returnValue);
            }
            printf ("\nIn checkServerExists ()`: thread id %ld\n", newThread [globalThreadIndex]);
    
            serverInfo obj;
            obj.serverId  = serverNumber;
            obj.threadId = newThread [globalThreadIndex];
            obj.queue.push_back (newThread [globalThreadIndex]);
            serverInfoVector.push_back (obj);
    
            // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.
    
            // Now, since something has been pushed in the vector, it makes sense to wake up the sleeping thread.
            pthread_cond_signal (&demoConditionVar);
    
            pthread_mutex_unlock(&demoMutex);
    
            pthread_join (newThread [globalThreadIndex], NULL);
        }
        else
        {
            pthread_mutex_unlock(&demoMutex);
        }
    }
    
    
    int main ()
    {
        fp = fopen ("xyz", "w");
        pthread_mutex_init (&demoMutex, NULL);
        pthread_cond_init (&demoConditionVar, NULL);
    
        checkServerExists (1, "anisha");
        globalThreadIndex++;
        checkServerExists (2, "anisha");
    
        return 0;
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

i'm working with TFS and i need to edit file localy without checking it
I want to edit .vimrc file from Vim and apply them without restarting Vim.
I have been told to edit this file in Sharepoint Designer: /_layouts/KWizCom_WikiPlus/CreateNew.aspx I found
Can I edit an excel file from a browser using POI? Something like google
How to edit the .fla file code and save it in the .swf format?
have downloaded Orca to edit an MSI file. I want to remove some banner
Is it possible to edit web.config file of my cloud app deployed on Windows
I am attempting to edit the default file located at .. /etc/apache2/sites-available/default on my
Does anybody know how to edit a syntax file for VIM so that keywords
I'm looking for a way to edit a configuration file (web.config in an asp.net

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.