Thread: How to use pthread_cond_wait() in c.

  1. #1
    Registered User
    Join Date
    Feb 2017
    Posts
    12

    How to use pthread_cond_wait() in c.

    So in my code, I'm adding and removing items from a bounded buffer and if an item cannot be added or removed then the code waits. This is the wait I'm using for add.
    Code:
        void add_to_buffer(int value) {
            pthread_mutex_lock(&mutex);
            while (count == BOUNDED_BUFFER_SIZE){
                pthread_cond_wait(&cond, &mutex);
            }
            bounded_buffer[count] = value;
            count++;
            pthread_cond_signal(&cv);
            pthread_mutex_unlock(&mutex);
        }
    Now when I test this, I have a server window and another window where I run curl commands. Now if I run enough add commands to the point where the buffer is full and it has to wait, I can't input another command on my terminal window while the server is waiting due to the fact that the mutex is locked. I tried opening up a new terminal window and do a remove command and it removes the value from the buffer however the previous add command doesn't add anything new to the bounded buffer.

    So did I not implement the wait correctly or am I not testing it correctly?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Who knows.
    Try posting the matching remove_from_buffer code.

    Better yet, Short, Self Contained, Correct Example
    Make a short main() with two threads.
    One thread adds to the buffer at random intervals.
    The other thread removes from the buffer at random intervals.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 03-04-2015, 11:27 AM
  2. pthread_cond_wait for binary semaphores
    By homer_3 in forum C Programming
    Replies: 2
    Last Post: 10-09-2009, 02:27 PM
  3. A quick question about pthread_cond_wait()
    By meili100 in forum C++ Programming
    Replies: 5
    Last Post: 09-28-2008, 01:18 PM
  4. A simple question about pthread_cond_wait()
    By meili100 in forum C++ Programming
    Replies: 6
    Last Post: 09-17-2008, 06:56 AM
  5. pthread_cond_wait() VS. sem_wait()
    By mynickmynick in forum C Programming
    Replies: 8
    Last Post: 05-07-2008, 10:28 AM

Tags for this Thread