VOOZH about

URL: https://www.geeksforgeeks.org/linux-unix/condition-wait-signal-multi-threading/

⇱ Conditional wait and signal in multi-threading - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Conditional wait and signal in multi-threading

Last Updated : 27 Jan, 2023

What are conditional wait and signal in multi-threading? 
Explanation: When you want to sleep a thread, condition variable can be used. In C under Linux, there is a function pthread_cond_wait() to wait or sleep. 
On the other hand, there is a function pthread_cond_signal() to wake up sleeping or waiting thread. 
Threads can wait on a condition variable. 

Prerequisite : Multithreading

Syntax of pthread_cond_wait() : 

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

Parameter :  

cond : condition variable
mutex : is mutex lock 

Return Value :  

On success, 0 is returned ; otherwise, an error 
number shall be returned to indicate the error. 

The pthread_cond_wait() release a lock specified by mutex and wait on condition cond variable. 

Syntax of pthread_cond_signal() :  

int pthread_cond_signal(pthread_cond_t *cond);

Parameter : 

cond : condition variable

Return Value :  

On success, 0 is returned ; otherwise, an error number
shall be returned to indicate the error. 

The pthread_cond_signal() wake up threads waiting for the condition variable. 

Note : The above two functions works together. 

Below is the implementation of condition, wait and signal functions.  

Output: 
 

👁 Image

Time Complexity: 
The time complexity of this program is O(1), as the program only requires one iteration of each thread.

Space Complexity: 
The space complexity of this program is O(1), as the program only requires a few variables to be stored in memory.

Comment

Explore