Producer consumer pthreads program not finishing

Producer consumer pthreads program not finishing

By : Nachtfalter
Date : November 21 2020, 03:00 PM
I wish this helpful for you So I have to make a program that uses 4 producer threads and 4 consumer threads, with an array that holds 10 random numbers at a time. Once that array is full, the producer must wait until those 10 numbers are consumed by the consumer, and then the consumer waits for the array to be full again. I have to do this with 1000 random numbers.
code :
    if (bufCounter == BSIZE){
        isFull = true;
        isEmpty = false;
    if (bufCounter == 0){
        isEmpty = true;
        isFull = false;

Share : facebook icon twitter icon
pthreads producer-consumer deadlock

pthreads producer-consumer deadlock

By : katie biernat
Date : March 29 2020, 07:55 AM
it helps some times You used cond_empty in both sides for the wait. You signal (but never wait on) cond_full.
producer-consumer problem with pthreads

producer-consumer problem with pthreads

By : user3091529
Date : March 29 2020, 07:55 AM
it should still fix some issue Both the consumer and producer does a sleep(rand()) which will sleep for a random number of seconds between 0 and MAX_INT, in the example you give the main thread will terminate after 10 seconds. If the rand() value of the producers are above 10 they will never have the chance produce anything.
Producer Consumer program using semaphores and pthreads

Producer Consumer program using semaphores and pthreads

By : ext3063
Date : March 29 2020, 07:55 AM
it fixes the issue Maybe you should take the Compiler warnings more serious. Incorrect types and undefined functions are usually shown as warning...
I haven't checked the Logic of your program, but the principle should work:
code :
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include </usr/include/semaphore.h>

// for sleep
#include <unistd.h>

#define BUFF_SIZE   5           /* total number of slots */
#define NP          3           /* total number of producers */
#define NC          3           /* total number of consumers */
#define NITERS      4           /* number of items produced/consumed */

typedef struct
    int buf[BUFF_SIZE];   /* shared var */
    int in;               /* buf[in%BUFF_SIZE] is the first empty slot */
    int out;              /* buf[out%BUFF_SIZE] is the first full slot */
    sem_t full;           /* keep track of the number of full spots */
    sem_t empty;          /* keep track of the number of empty spots */

    // use correct type here
    pthread_mutex_t mutex;          /* enforce mutual exclusion to shared data */
} sbuf_t;

sbuf_t shared;

void *Producer(void *arg)
    int i, item, index;

    index = (int)arg;

    for (i=0; i < NITERS; i++)

        /* Produce item */
        item = i;

        /* Prepare to write item to buf */

        /* If there are no empty slots, wait */
        /* If another thread uses the buffer, wait */
        shared.buf[shared.in] = item;
        shared.in = (shared.in+1)%BUFF_SIZE;
        printf("[P%d] Producing %d ...\n", index, item);
        /* Release the buffer */
        /* Increment the number of full slots */

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    return NULL;

void *Consumer(void *arg)
    int i, item, index;

    index = (int)arg;
    for (i=NITERS; i > 0; i--) {
        shared.out = (shared.out+1)%BUFF_SIZE;
        printf("[C%d] Consuming  %d ...\n", index, item);
        /* Release the buffer */
        /* Increment the number of full slots */

        /* Interleave  producer and consumer execution */
        if (i % 2 == 1) sleep(1);
    return NULL;

int main()
    pthread_t idP, idC;
    int index;

    sem_init(&shared.full, 0, 0);
    sem_init(&shared.empty, 0, BUFF_SIZE);
    pthread_mutex_init(&shared.mutex, NULL);
    for (index = 0; index < NP; index++)
        /* Create a new producer */
        pthread_create(&idP, NULL, Producer, (void*)index);
    /*create a new Consumer*/
    for(index=0; index<NC; index++)
        pthread_create(&idC, NULL, Consumer, (void*)index);

producer/consumer using Pthreads and Semaphores

producer/consumer using Pthreads and Semaphores

By : Krishna Priya
Date : March 29 2020, 07:55 AM
around this issue 1) The = operator on a string copies by value. The following code is copying by value into the 'buffer' variable. However, later you are using p1_string in an infinite loop expecting it to update. Assigning a new value to the pthread_param.buffer does not change the value of px_string. Thus, in this case the strings will always equal their initial value and string 1 will always be less than string 2.
code :
pt1_param.buffer = p1_string; //assignment by value
pt2_param.buffer = p2_string; //assignment by value
while (1)
    if (!getline(buffer))
Logic error in my defined Mutex class and the way I use it in producer consumer program - pthreads

Logic error in my defined Mutex class and the way I use it in producer consumer program - pthreads

By : Felipe Morselli
Date : March 29 2020, 07:55 AM
hop of those help? Currently, you initialize mutexVariable to PTHREAD_MUTEX_INITIALIZER every time you create a new construct a new MutexClass. Consider what happens if thread A holds the mutexVariable and thread B wants to acquire the mutex:
code :
thread A tries to lock mutexVariable and succeeds

thread B tries to lock mutexVariable and succeeds
    // this assignment overwrites the locked state thread A has stored
    // mutex is default-initialized (not locked) - so lock it
    // both threads now believe they have the mutex
    // and all syncronization is lost

thread B unlocks mutexVariable
    // succeeds

thread A unlocks mutexVariable
    // uh.. it is not even locked any more?!
pthread_mutex_t mutexVariable = PTHRAED_MUTEX_INITIALIZER;
Related Posts Related Posts :
  • OpenGL - Uniform not being passed properly?
  • C++ Visual Studio "Non-standard syntax; use '&' to create a pointer to member"
  • Doxygen won't resolve reference to typedef in namespace
  • How to test for assert in debug build, but returned value in release?
  • use boost spirit parse int pair to vector
  • How #define works in Programming when define has value with operator?
  • C++: Passing objects by value to a member function of the same class
  • Confusion in C++ constructor
  • Implicit conversion operator doesn't kick in with operator overloading
  • From tuple of N elements to tuple of N/2 pairs
  • Operators Not Working With Class Objects?
  • GDAL Not Linking
  • C++ aligning characters to display neatly with any input implemented
  • c++, method to display content in hash table.Using double linked list
  • How to apply a function to a variadic argument list and cat them to a tuple
  • Doubly linked list c++ crashing after 3rd node
  • Transform a specific type of argument using templates
  • Function with recursion is causing stack overflow
  • working with multi-word typedefs
  • Calling std::to_string or std::to_wstring based on given typedef
  • Ensure a `std::vector` won't move its pointer
  • Appopriate Container that acts like normal static array?
  • Using enable_if to disable a template constructor of a template class
  • define implicit conversion from template class to primitive type based on other template
  • C++ class template, how to overload [ ] operator in a specific stuation?
  • What is the purpose of using an iterator in this function's return value?
  • C++ overriding the value of inherited static const variables
  • C++: what is special about punning character arrays according to the standard?
  • How do I start two thread teams with different thread functions at the same time?
  • OpenGL 3.3: GL_INVALID_OPERATION when calling glBindBuffer
  • Boost Karma generator for composition of classes
  • Can the storage of trivially copyable objects be safely reallocated with realloc?
  • Can I force a C++ class to be non-abstract?
  • The QPropertyAnimation is automatically deleted when using QParallelAnimationGroup?
  • Failing to specialize function for function pointer
  • Check if two (smart) pointers point to the same derived class
  • Getting an error when using delete[] cpp
  • recursion in variadic template function of different argument types
  • QTWidgets QTableWidget crash with segfault
  • clang and clang++ with ASAN generate different output
  • How to map BYTE array as FILE * on Windows
  • Logic Error With Function to Manipulate Linked List
  • Expected primary-expression before numeric constant
  • Pre-Decrement Operator
  • C++: how to input values separated by comma(,)
  • Correct way to write operator+ using rvalues
  • How to ignore whitespace and punctuation?
  • Prevent duplicated code on different data types (uint16_t/ uint32_t)
  • Writing Custom FPrintF
  • How to read from keyboard a complete random text, filter and cast
  • SIGSEGV when trying to change string in structure C/C++
  • c++: tuple with tag-type access
  • C++ initializing pointer crashes application randomly?
  • Options to replace deprecated DirectSound
  • how pass TextField text from QString in C++?
  • Undefined Behaviour: value of array element changes implicitly/illogically
  • OpenGL texture format, create image/texture data for OpenGL
  • [Boost]::DI creating unique shared_ptr objects from injector
  • What is the effect of ordering if...else if statements by probability?
  • Valgrind error: Syscall param epoll_pwait(sigmask) points to unaddressable byte(s)
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org