Detailed Linux mutex Pthread_mutex and condition variable Pthread_cond

Source: Internet
Author: User
Tags mutex

[CPP] View plaincopy =============================================================intpthread_create (pthread_t*Tid,Constpthread_attr_t *attr,void* (*start_routine) (void*),                  void*Arg); //The parameter tid is used to return the thread number of the newly created thread;//Start_routine is a thread function pointer, and the thread starts running independently from this function;//Arg is the argument passed to the thread function.   Because Start_routine is a pointer to the parameter type void* and returns a value of void*, you can use forced type conversions if you need to pass or return more than one parameter. =============================================================voidPthread_exit (void*value_ptr); //The parameter value_ptr is a pointer to the return status value. =============================================================intpthread_join (pthread_t tid,void**status); //The parameter tid is the thread number of the thread you want to wait for, status is a pointer to the return value of the thread, the return value of the thread is the value_ptr parameter in Pthread_exit, or the return value in the return statement.   This function can be used for synchronization between threads. =============================================================intPthread_mutex_init (pthread_mutex_t*Mutex,Constpthread_mutex_attr_t*attr); //The function initializes a mutex variable, and if the parameter attr is null, the mutex//the body variable mutex uses the default property. =============================================================intPthread_mutex_lock (pthread_mutex_t*mutex); //This function is used to lock the mutex variable. If the mutex referred to by the parameter mutex is already//is locked, the thread that makes the call is blocked until the other thread unlocks the mutex. =============================================================intPthread_mutex_trylock (pthread_t*mutex); //This function is used to lock the mutex specified by the mutex without blocking it. If the mutex//the body has been locked, the call does not block the wait, and an error code is returned. =============================================================intPthread_mutex_unlock (pthread_mutex_t*mutex); //This function is used to unlock a mutex. If the current thread owns the parameter mutex//specifies the mutex that the call will unlock. =============================================================intPthread_mutex_destroy (pthread_mutex_t*mutex); //The function is used to release the resource assigned to the parameter mutex. When the call succeeds, the return value is//0, otherwise a non-0 error code is returned. =============================================================intPthread_cond_init (pthread_cond_t*Cond,Constpthread_cond_attr_t*attr); //The function creates a condition variable according to the property specified by the parameter attr. The call returned successfully,//The condition variable ID is assigned to the parameter cond, otherwise the error code is returned. =============================================================intpthread_cond_wait (pthread_cond_t*Cond, pthread_mutex_t*mutex); //The function call is unlocked for the mutex specified by the parameter mutex, waiting for an event (by the//parameter cond the specified condition variable) occurs. The thread that called the function is blocked until there are other//the thread calls the Pthread_cond_signal or Pthread_cond_broadcast function to place the corresponding bar//the mutex mutex is not unblocked. =============================================================intpthread_cond_timewait (pthread_cond_t*Cond, pthread_mutex_t*Mutex,Const structTimespec *abstime); //This function differs from pthread_cond_wait in that the blocked thread can also be called to continue execution when the system time reaches the time specified by the Abstime parameter. =============================================================intPthread_cond_broadcast (pthread_cond_t*cond); //This function is used to unblock all threads that wait for the condition variable specified by the parameter cond, and the call returns 0 successfully, otherwise an error code is returned. =============================================================intpthread_cond_signal (pthread_cond_t*cond); //The function is to dismiss a blocking state for a thread that waits for the condition variable specified by the parameter cond.   When there are multiple threads pending waiting for the condition variable, only one thread is awakened. =============================================================intPthread_cond_destroy (pthread_cond_t*cond); //The function is to release a condition variable. Releases the resources allocated for the cond of the condition variable.   The call succeeds with a return value of 0, otherwise an error code is returned. =============================================================intpthread_key_create (pthread_key_t key,void(*destructor (void*))                      ); //The function creates a key value that maps to a proprietary data structure body.   If the second parameter is not NULL, the function pointer is called to free the data space when the key value is deleted. =============================================================intPthread_key_delete (pthread_key_t*key); //This function is used to delete a TSD key created by the Pthread_key_create function call.   The call succeeds with a return value of 0, otherwise an error code is returned. =============================================================intpthread_setspecific (pthread_key_t key,Const void(value)); //This function sets the value of a thread-specific data to the TSD key created by Pthread_key_create, which returns a successful return value of 0, otherwise returns an error code. =============================================================void*pthread_getspecific (pthread_key_t*key); //The function obtains the value bound to the specified TSD key. The call succeeds and returns the data corresponding to the given parameter key.   If no data is connected to the TSD key, NULL is returned. =============================================================intpthread_once (pthread_once_t*Once_control,void(*init_routine) (void)                ); //The function is to ensure that the function that Init_routine points to is only run once in the thread that calls Pthread_once.   Once_control points to a static or global variable. =============================================================In code review, I'll find a lot of people like to call pthread_cond_signal or pthread_cond_ between Pthread_mutex_lock () and Pthread_mutex_unlock () The broadcast function, logically speaking, is completely correct. However, in a multithreaded environment, this method of use may be inefficient. The POSIX1 Standard says that pthread_cond_signal and pthread_cond_broadcast do not need to consider whether the calling thread is the owner of the mutex, that is, it can be called in areas other than lock and unlock. If we do not care about the invocation behavior, please call outside the lock area. Here's an example: we assume that the system is wired 1 and thread 2, they all want to get the mutex to process the shared data, and then release the mutex. Take a look at this sequence:1Thread 1 acquires the mutex, and thread 2 also wants to acquire the mutex while the data is being processed, but at this point it is occupied by thread 1, thread 2 goes into hibernation and waits for the mutex to be released. 2after thread 1 finishes processing, call Pthread_cond_signal () to wake up a thread in the wait queue, in this case thread 2. Thread 1 before calling Pthread_mutex_unlock (), because the system is scheduled for the reason that thread 2 gets the right to use the CPU, then it wants to start processing the data, but before starting processing, the mutex must be fetched, unfortunately, thread 1 is using the mutex,      So thread 2 was forced to go into hibernation again. 3after that, thread 1 executes pthread_mutex_unlock () and thread 2 can be awakened again.   From this point of view, the use of efficiency is relatively low, if the multi-threading environment, this situation occurs frequently, it is a more painful thing. Therefore, if the program does not care about the predictable scheduling behavior of threads, it is better to call them outside of the locked area:-) if the reader likes English, please refer to: http://www.opengroup.org/onlinepubs/007908799/xsh/pthread_cond_broadcast.htmlHere's a few words, forintPthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); intPthread_cond_timedwait (pthread_cond_t *Cond, pthread_mutex_t*mutex,Const structTimespec *abstime);   , be sure to use it within the locked area of the mutex. If you want to use Pthread_mutex_lock and pthread_mutex_unlock correctly, refer to Pthread_cleanup_push and Pthread_cleanup_pop macros,   It is able to properly release mutex! when the thread is cancel http://blog.csdn.net/hello_wyq/archive/2006/08/23/1108264.aspxPthread_cond (3) name Pthread_cond_init, Pthread_cond_destroy, Pthread_cond_signal, Pthread_cond_broadcast, Pthread_cond_wait, PT Hread_cond_timedwait-state operation. Outline #include pthread_cond_t cond=Pthread_cond_initializer; intPthread_cond_init (pthread_cond_t *cond, pthread_condattr_t *cond_attr); intPthread_cond_signal (pthread_cond_t *cond); intPthread_cond_broadcast (pthread_cond_t *cond); intPthread_cond_wait (pthread_cond_t *cond, pthread_mutex_t *mutex); intPthread_cond_timedwait (pthread_cond_t *cond, pthread_mutex_t *mutex,Const structTimespec*abstime); intPthread_cond_destroy (pthread_cond_t *cond); Describing a state variable is a synchronous device that allows a thread to suspend and discard CPU time to wait for certain shared variables to satisfy the state.   Basic operation of the action state variable: sends a signal when the state is satisfied, waits for the state to meet, suspends the thread before another thread sends a status signal.   State variables are usually associated with mutexes, in order to avoid a competing state, a thread is ready to wait for a state variable before another thread sets the state signal first. Pthread_cond_init initializes the state variable cond, using the state attribute defined in Cond_attr, and if cond_attr is NULL, the default property will be used.   The implementation of Linuxthreads supports cond_attr without any attributes, so cond_attr is ignored.   Variables of type pthread_cond_t can also be statically initialized using Pthread_cond_initializer. Constants. The pthread_cond_signal function restarts a thread that is waiting for the cond variable. If no thread is waiting for the cond variable, no action is taken.   If more than one thread is waiting, a matching thread is restarted, but not necessarily. The Pthread_cond_broadcast function restarts all threads that are waiting for the cond variable.   If no thread is waiting for the cond variable, no action is taken. The Pthread_cond_wait function atomically unlocks the mutex (like Pthread_unlock_mutex) and waits for the status signal. The thread is suspended and does not consume CPU time until the status signal is sent. The mutex must be locked by the caller.   The mutex is owned by Pthread_cond_wait before returning the calling thread. Releasing the mutex and suspending it on the state variable is automatic.   Therefore, if all threads often ask for a mutex before the status signal, this guarantees that the thread will not trigger the signal during the period state variable that locks the mutex on the state variable. The Pthread_cond_timedwait function automatically releases the mutex and waits for the cond state, just as Pthread_cond_wait did, but it limits the maximum wait time. If cond does not make a mark in a certain amount of time with no time specified in the Abstime, the mutex is obtained again, and then the error code etimeout is returned. The Abstime parameter specifies the absolute time, and the duration (2) and Gettimeofday (2): Starting at 0 o'clock GMT January 1, 1970. The Pthread_cond_destroy function destroys the state variable, releasing the resources it may hold. No thread has to wait for the state variable here.   In the Linuxthreads implementation, the state variable is not related to any resources, so this interface does nothing except check for the waiting thread on the state variable. Canceling pthread_cond_wait and pthread_cond_timedwait are all cancellation points. If a thread is suspended and then canceled in one of these functions, the thread restarts execution and then locks the mutex. (not yet completed!) The synchronous signal security state function is not synchronous and should not appear in the signal processing function.   In particular, calling Pthread_cond_signal or pthread_cond_broadcast from a signal processing function can cause deadlocks.   Return value all state variable functions return 0 on success and return an error code when an error occurs.   Error codes Pthread_cond_init, Pthread_cond_signal, Pthread_cond_broadcast, and pthread_cond_wait never return error codes.   The Pthread_cond_timedwait function returns the following error code on Error: etimeout: The state variable has no excitation signal within the abstime time limit.   The eintr:pthread_cond_timedwait is interrupted by a signal.   The Pthread_cond_destroy function returns the following error code on Error: Ebusy: Thread is waiting on cond. Author Xavier Leroy See Pthread_condattr_init (3), Pthread_mutex_lock (3), Pthread_mutex_unlock (3) Gettimeofday (2), Nanosleep (2).   The example considers two shared variables x and y, protected with a mutex mut, and a state variable cond the signal when x is greater than Y. intx, y; pthread_mutex_t Mut=Pthread_mutex_initializer; pthread_cond_t Cond=Pthread_cond_initializer; Wait until x is greater than Y:pthread_mutex_lock (&mut);  while(x <=y) {pthread_cond_wait (&cond, &mut); }   /*operate on X and Y*/Pthread_mutex_unlock (&mut); modifying x and Y may cause X to be greater than Y. Signal should be sent if needed: Pthread_mutex_lock (&mut); /*modify x and y*/   if(x > Y) pthread_cond_broadcast (&cond); Pthread_mutex_unlock (&mut); If you can prove that at most one waiting thread needs to wake up (for example, only two threads, linked by x and y), pthread_cond_signal can be an optional, more efficient lightweight pthread_cond_broadcast.   If you are unsure, use the Pthread_cond_broadcast function. To wait within 5 seconds X is greater than Y, like this:structTimeval now; structtimespec timeout; intRetcode; Pthread_mutex_lock (&mut); Gettimeofday (&Now ); Timeout.tv_sec= Now.tv_sec +5; Timeout.tv_nsec= Now.tv_usec * +; Retcode=0;  while(x <= y && retcode! =etimedout) {Retcode= Pthread_cond_timedwait (&cond, &mut, &timeout); }   if(Retcode = =etimedout) {   /*Timeout occurred*/   } Else {   /*operate on X and Y*/} pthread_mutex_unlock (&mut); 

Detailed Linux mutex Pthread_mutex and condition variable Pthread_cond

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.