Conditional variable (correlation function)

Conditional variable concept

effect
Condition variables are used to communicate between multithreads about changes in the state of shared data. When an action needs another action to complete, that is, when the behavior of one thread depends on the change of shared data state by another thread, condition variables can be used.
 
It must be used together with the mutex. The reason why the condition variable is used together with the mutex is mainly because the mutex has only two states: locked and unlocked. The condition variable can make up for the deficiency of the mutex by allowing the thread to block and wait for another thread to send a signal, So mutexes and conditional variables are usually used together.
 
Conditional variable itself is not a lock, but it can also cause thread blocking. It is usually used in conjunction with mutex to provide a meeting place for multiple threads.

correlation function

pthread_cond_init initialization

Prototype:
  int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);

Function:
Initialize a condition variable

Parameters:
cond: condition variable
attr: condition variable attribute, usually NULL, indicating that the default attribute is used
  
return:
Success: 0
Failed: error (error number)

pthread_cond_wait wait condition variable is satisfied

Prototype:
  int pthread_cond_wait(pthread_cond_t *restrict cond,pthread_mutex_t *restrict mutex);

Function:
Blocking waits for a condition variable (waiting for wake-up) and unlocks the corresponding lock resource
 
Parameters:
cond: condition variable
Mutex: mutex
  
return:
Success: 0
Failed: error (error number)

be careful:
Wake up, pthread_ cond_ When the wait function returns, unblock and reapply to obtain the mutex

pthread_cond_broadcast wakes up all threads waiting for condition variables

Prototype:
  int pthread_cond_broadcast(pthread_cond_t *cond);

Function:
Wake up all threads waiting for condition variables
 
Parameters:
cond: condition variable
  
return:
Success: 0
Failed: error (error number)

pthread_cond_signal wakes up a thread waiting for a condition variable

Prototype:
  int pthread_cond_signal(pthread_cond_t *cond);

Function:
Wake up a thread waiting for condition variables (wake up one at random)
 
Parameters:
cond: condition variable
  
return:
Success: 0
Failed: error (error number)

pthread_cond_destroy destroy condition variable

Prototype:
  int pthread_cond_destroy(pthread_cond_t *cond);

Function:
Destroy condition variable
 
Parameters:
cond: condition variable
  
return:
Success: 0
Failed: error (error number)

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <string.h>


pthread_mutex_t  mutex;     //Define mutex
pthread_cond_t   cond;      //Define a condition variable

int k ;

void *routine(void *arg);
void function(void *arg);

int main()
{

	pthread_mutex_init(&mutex, NULL);    //Initialize mutex
    pthread_cond_init(&cond,NULL);       //Initialize condition variable
		
	pthread_t id[5];//Define a thread ID number
    for(int i = 0; i < 5; i++)  //Create five threads
    {
	    pthread_create((id + i), NULL, routine, NULL);//Create thread id number and save address
        printf("Thread created%ld\n",id[i]);
    }
	
	while(1)    //Cyclic locking
	{
		pthread_mutex_lock(&mutex); //Lock

        if(k == 0)      
        {
            printf("Please enter k Value of:");
            scanf("%d",&k);
        }

        pthread_cond_broadcast(&cond);  //Wake up all waiting threads

		pthread_mutex_unlock(&mutex);//Unlock
        sleep(1);
	}
	
	pthread_mutex_destroy(&mutex);//Destroy mutex

	pthread_exit(NULL);
}

//Thread function
void *routine(void *arg)
{
	pthread_t id = pthread_self();
    sleep(1);
	while(1)
	{
        
		pthread_mutex_lock(&mutex);//Lock
		pthread_cleanup_push(function,NULL);    //Function stack (thread cleanup function)

        if(k > 0)       //If the conditions are met, perform the following procedures
        {
            printf("%ld I got the resources\n",id);
            k--;
        }
        else
        {
            pthread_cond_wait(&cond,&mutex);    //Wait to wake up and unlock the corresponding lock resource
        }

        pthread_mutex_unlock(&mutex); //Unlock
        pthread_cleanup_pop(0);     //Normal exit does not execute thread cleanup function

        sleep(1);
	}

	return NULL;
}


//Cleanup function (deadlock prevention)
void function(void *arg)
{
    printf("Yo, what's the matter\n");

    //Unlock (prevent deadlock caused by abnormal thread termination)
    pthread_mutex_unlock(&mutex);

}

Tags: C

Posted on Thu, 07 Oct 2021 16:22:26 -0400 by fishown