pthread_cond_broadcast --- pthread_cond_signal --- pthread_cond_wait difference

1. Applicable to pthread_cond_broadcast

1. One producer has many consumers, and the producer can produce many products at one time.
2. Multiple producers and multiple consumers
 3. Implementation of read-write lock (notify all readers after writing)
//test.c
#include<stdio.h>
#include<unistd.h>
#include<pthread.h>
#define MAX_THREAD_NUM 5
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void* thread_fun(void* arg)
{
    int index = *(int*)arg;
    printf("[%d]thread start up!\n", index);
    pthread_mutex_lock(&mutex);
    printf("[%d]thread wait...\n", index);
    pthread_cond_wait(&cond, &mutex);
    printf("[%d]thread wake up\n", index);
    pthread_mutex_unlock(&mutex);
    pthread_exit(0);
}
int main()
{
    pthread_t tid[MAX_THREAD_NUM];
 
    for(int i = 0; i < MAX_THREAD_NUM; i++)
    {
        pthread_create(&tid[i], NULL, thread_fun, &i);
        sleep(1);
    }
    sleep(3);
    //pthread_ cond_ & signal; / / wake up one of N threads
    pthread_cond_broadcast(&cond);	//Wake up all
    for(int i = 0; i < MAX_THREAD_NUM; ++i)
    {
        pthread_join(tid[i], NULL);
    }
    return 0;
}

 pthread_cond_signal can only wake up one of N threads, while pthread_cond_broadcast can wake up all n threads.

2. Applicable to pthread_ cond_ About signal

pthread_ cond_ The signal() function is used to send a signal to another thread that is in the blocking waiting state, so that it can get out of the blocking state and continue to execute. If no thread is in the blocking waiting state, pthread_cond_signal will also return successfully.

1. Single producer, where the producer produces one product at a time, the best one consumer
 2. Note: pthread_cond_signal is not safe in the case of a single asynchronous wake-up processing thread
//Pseudocode
pthread_mutex_t mul;
pthread_cond_t cond;
 
pthread_mutex_lock(&mul);  //Lock up
/***
    Perform operations on data
                ****/
pthread_cond_signal(&cond);  //Wake up other blocked threads based on cond condition
pthread_mutex_unlock(&mul);  //Unlock

 3. pthread_cond_wait() function

 pthread_ cond_ The signal() function may wake up multiple threads at the same time on multiple processors. When you can only let one thread handle a task, other waked threads need to continue to wait

//Pseudocode
pthread_mutex_t mul;
pthread_cond_t cond;
 
pthread_mutex_lock(&mul);  //Lock up
while(condition){
    pthread_cond_wait(&cond,&mul);  //If the condition is not satisfied, the data operation will be performed
}
/***
    Perform operations on data
                ****/
pthread_mutex_unlock(&mul);  //Unlock

Posted on Tue, 19 May 2020 12:48:57 -0400 by icaro