0

This might seem a basic question but please bear with me.

I need to develop a multi-threaded program which has numerous threads waiting for the main to assign them work (something along the lines of a producer consumer thread). I have condition variables to alert the threads to stop waiting and start working and then go back to wait state. I have a mutex on the condition variable which would be locked and under the control of the main thread. I call function def() on worker threads.

Main thread

    int def(int y)
   {
    // Signal the worker threads to stop waiting and start working
    pthread_cond_signal(&condvar);
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&condvar1, &mutex);
    pthread_mutex_unlock(&mutex);
    fprintf(stderr, "\nInside the thread");
    return 0;

   }



int init()
    {
    // Initialize the thread condition variables
        pthread_mutex_init(&mutex, NULL);
        pthread_cond_init(&condvar, NULL);
        pthread_cond_init(&condvar1, NULL);
        int x=0;

        if(pthread_create(&mythread, NULL, abc, &x)) {
                fprintf(stderr, "Error creating thread\n");

        }

        return 0;
   }

My issue is that the program is time sensitive and lock instructions take a few thousand nanoseconds.

My question is that can i interact with the threads and keep them waiting without using mutex locks? I have independent worker threads which do not access each other's data. The main and the worker thread pass each other data.

What is the correct way to go about it?

JRD
  • 37
  • 2
  • What have you tried other than mutexes and condition variables? You can use semaphores. You can use a [pipe](http://pubs.opengroup.org/onlinepubs/9699919799/functions/pipe.html) as a queue for distributing work (write a pointer value to the pipe, worker threads read the pointer value from the pipe). You can try lock-free queues (while those [tend not to work very well](https://stackoverflow.com/questions/43540943/using-boost-lockfree-queue-is-slower-than-using-mutexes), maybe they'll work well for you). There is no "correct way". – Andrew Henle Aug 16 '18 at 10:36

1 Answers1

0

The reason to use a mutex :

A condition variable must always be associated with a mutex, to avoid the race condition where a thread prepares to wait on a condition variable and another thread signals the condition just before the first thread actually waits on it.

You should use it before pthread_cond_signal and before pthread_cond_wait.

I guess you don't need a condition variable.

lue
  • 25
  • 6