In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Servers >
Share
Shulou(Shulou.com)06/01 Report--
This article is about how Linux implements conditional variables. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
Condition variables are used to wait for threads rather than lock them, and they are usually used with mutexes. Conditional variables are used with mutexes mainly because one of the obvious features of mutexes is that they have only two states: locked and non-locked. condition variables can make up for the deficiency of mutexes by allowing threads to block and wait for another thread to send a signal, so mutexes and condition variables are usually used together.
When the condition is met, the thread usually unlocks and waits for the condition to change. Once another thread modifies the environment variable, it will notify the corresponding environment variable to wake up one or more threads blocked by the condition variable. These awakened threads will be re-locked and tested to see if the conditions are met. In general, conditional variables are used for synchronization between threads; when the conditions are not met, one of the execution flows is allowed to suspend and wait.
In short, a conditional variable is not a lock itself, but it can also cause thread blocking and is usually used in conjunction with mutexes to provide a rendezvous place for multiple threads.
Advantages of conditional variables:
Compared with mutex, conditional variables can reduce competition. If it is only mutex, then, regardless of whether there is data in the shared resources, producers and all consumers will swarm to grab the lock, which will result in a waste of resources.
If you use mutex directly, in addition to competing mutexes between producers and consumers, consumers also need competitive mutexes, but if there is no data in the aggregation (linked list), competitive mutexes between consumers are meaningless. With the conditional variable mechanism, only when the producer completes the production, will it cause the competition among consumers. The efficiency of the program is improved.
Main application functions:
Pthread_cond_init function
Pthread_cond_destroy function
Pthread_cond_wait function
Pthread_cond_timedwait function
Pthread_cond_signal function
Pthread_cond_broadcast function
The return values of the above six functions are: 0 for success and error number for failure.
Pthread_cond_t type: used to define condition variables, such as pthread_cond_t cond
# # pthread_cond_init function
Function prototype:
Int pthread_cond_init (pthread_cond_t restrict cond, const pthread_condattr_t restrict attr)
Function function: initializes a conditional variable
Parameter description:
Cond: conditional variable, which should be passed & cond to the function when called
Attr: condition variable attribute. NULL is usually passed, which means the default attribute is used.
You can also initialize the condition variable using the method of static initialization:
Pthread_cond_t cond = PTHREAD_COND_INITIALIZER
# # pthread_cond_destroy function
Function prototype:
Int pthread_cond_destroy (pthread_cond_t * cond)
Function function: destroy a conditional variable
# # pthread_cond_wait function
Function prototype:
Int pthread_cond_wait (pthread_cond_t restrict cond, pthread_mutex_t restrict mutex)
Function function:
Blocking waits for a condition variable. Specifically, it has the following three functions:
The blocking wait condition variable cond (Ref 1) is satisfied.
Releasing the mastered mutex mutex (unlocking mutex) is equivalent to pthread_mutex_unlock (& mutex)
When awakened and the pthread_cond_wait function returns, unblock and reapply for the mutex
Among them, 1, 2. Two steps are one atomic operation.
# # pthread_cond_timedwait function
Function prototype:
Int pthread_cond_timedwait (pthread_cond_t restrict cond, pthread_mutex_t restrict mutex, const struct timespec * restrict abstime)
Function function: waiting for a conditional variable for a limited time
Parameter description:
The first two are easy to understand, focusing on the third parameter.
There is a struct timespec structure that can be viewed in man sem_timedwait. The prototype of the structure is as follows:
Struct timespec {time_t tv_sec; / seconds / second long tv_nsec; / nanosecondes/ nanosecond}
The parameter abstime defined by struct timespec is an absolute time. Note that it is absolute time, not relative time. What is absolute time? 10:10:00 on October 1st, 2018, this is an absolute time. What is relative time? Timing the washing machine for 30 minutes is a relative time, that is, 30 minutes from the time at that time, and so on.
For example, time (NULL) returns absolute time. Alarm (1) is the relative time, which is timed for 1 second relative to the current time.
The relative time of adstime is relative to 00:00:00 on January 1, 1970, the first year of UNIX timing.
Here is a misuse: struct timespec t = {1,0}; pthread_cond_timedwait (& cond, & mutex, & t); this usage can only be timed to 00:00:01 seconds on January 1, 1970, when no one must have been born yet.
Correct usage: time_t cur = time (NULL); get the current time. Struct timespec t; defines the timespec structure variable t t.tv_sec = cur+1; timing 1 second pthread_cond_timedwait (& cond, & mutex, & t); pass parameters
# # pthread_cond_signal function
Function prototype:
Int pthread_cond_signal (pthread_cond_t * cond)
Function function: wakes up at least one thread blocking on a condition variable
# # pthread_cond_broadcast function
Function prototype:
Int pthread_cond_broadcast (pthread_cond_t * cond)
Function function: wakes up all threads blocking on condition variables
# # producer-Consumer condition variable Model
No matter what language it is, whenever thread synchronization is mentioned, a typical case is the producer-consumer model. In Linux environment, it is a common method to realize this model with the help of conditional variables.
Suppose there are two threads, one that simulates producer behavior and one that simulates consumer behavior. Two threads operate on a shared resource (commonly known as aggregation) at the same time, production adds products to it, and consumers consume products from them.
Take a look at the following example, using conditional variables to simulate producer and consumer problems:
# include # include typedef struct msg {struct msg * next; int num;} msg_t;msg_t * head = NULL;msg_t * mp = NULL;/* statically initialize a condition variable and a mutex * / pthread_cond_t has_product = PTHREAD_COND_INITIALIZER;pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER Void * th_producer (void * arg) {while (1) {mp = malloc (sizeof (msg_t)); mp- > num = rand ()% 1000; / / simulate the production of a product printf ("--produce:% d -\ n", mp- > num); pthread_mutex_lock (& mutex); mp- > next = head; head = mp Pthread_mutex_unlock (& mutex); pthread_cond_signal (& has_product); / / Wake up threads to consume the product sleep (rand ()% 5);} return NULL;} void * th_consumer (void * arg) {while (1) {pthread_mutex_lock (& mutex) While (head = = NULL) {/ / if there is no product in the linked list, there is no need to grab the lock, blocking and waiting for pthread_cond_wait (& has_product, & mutex);} mp = head; head = mp- > next; / / simulates the consumption of a product pthread_mutex_unlock (& mutex) Printf ("= consume:% d =\ n", mp- > num); free (mp); mp = NULL; sleep (rand ()% 5);} return NULL;} int main () {pthread_t pid, cid; srand (time (NULL)); pthread_create (& pid, NULL, th_producer, NULL); pthread_create (& cid, NULL, th_consumer, NULL) Pthread_join (pid, NULL); pthread_join (cid, NULL); return 0;}
Running result:
Thank you for reading! This is the end of the article on "how to achieve conditional variables in Linux". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.