-1

I got this simple C program that uses pthreads.

I basically want to call my_function() once I'm 100% sure that my_thread() gets called and is executed.

I need to know how to synchronize the main() function and the my_thread() function.

Please note that the my_thread() never returns.

#include <stdio.h>

#include <pthread.h>


void  my_function (void);
void* my_thread (void* arg);


int main (int argc, char* argv[])
{
    int rc;
    pthread_t id;
    
    rc = pthread_create(&id, NULL, my_thread, NULL);
    if (rc != 0)
    {
        return -10;
    }
    
    
    /*
     * I wanna call my_function() once I'm 100% sure my_thread() gets called and being executed
     */
    

    /*
     * Synchronization code to add here:
     */     
    
    
    my_function();
    
    
    return 0;
}


void* my_thread (void* arg)
{
    
    /*
     * This pthread never returns
     */
     
    while (1)
    {
        /* stuff */
    };
    
}

void my_function (void)
{
    printf("Hello\n");
}

Thanks for your help.

Promila Ghosh
  • 389
  • 4
  • 12
Enrico Migliore
  • 201
  • 3
  • 9
  • [Here](https://stackoverflow.com/questions/12282393/how-to-synchronize-manager-worker-pthreads-without-a-join) are some answers using *mutex* and *wait condition* – mmixLinus Dec 14 '21 at 08:37
  • As far as I see `my_thread()` never stops. Where is the synchronization point in this thread? – tstanisl Dec 14 '21 at 08:42
  • My actual thread function does some work. I want to call my_function() after the my_thread() gets called. – Enrico Migliore Dec 14 '21 at 09:02

1 Answers1

-1

Can anybody check if this solution is correct?

It works using the debugger but I would like to have a comment from experienced programmers.

#include <stdio.h>    
#include <pthread.h>
    
void  my_function (void);
void* my_thread (void* arg);

int started;
pthread_mutex_t mutex;   
pthread_t id;

int main (int argc, char* argv[])
{
    int rc;
    int done;       
            
    started = 0;
    mutex = PTHREAD_MUTEX_INITIALIZER;
    
    rc = pthread_create(&id, NULL, my_thread, NULL);
    if (rc != 0)
    {
        return -10;
    }
    
    
    /*
     * Synchronization code proposed:
     */             
    done = 0;
    do
    {
        
        pthread_mutex_lock(&mutex);

        if (started == 1)
        {
            done = 1;
        }

        pthread_mutex_unlock(&mutex);
        
    } 
    while (done == 0);
    
    
     /*
      * I wanna call my_function() once I'm 100% sure
      * that my_thread() is called and being executed
      */

    my_function();
    
    
    return 0;
}


void* my_thread (void* arg)
{
        
    started = 1;
    
    while (1)
    {
        /* stuff */
    };
    
}

void  my_function (void)
{
    printf("Hello\n");
}
Enrico Migliore
  • 201
  • 3
  • 9