Introduction to attributes of pthread_mutex_lock ()

Source: Internet
Author: User
Pthread_mutex_lock

Pthread_mutex_lock (pthread_mutex_t * mutex );

Int pthread_mutex_trylock (pthread_mutex_t * mutex );

Int pthread_mutex_unlock (pthread_mutex_t * mutex );

Description: The pthread_mutex_lock () function locks the mutex object specified by mutex. If mutex is locked, the thread that calls this function is blocked until mutex is available. This is the same as the mutex object specified by the mutex parameter returned by the function. At the same time, the call thread of the function becomes the owner of the mutex object.

If the mutex object type is pthread_mutex_normal, No Deadlock Detection (Deadlock Detection) is performed ). Attempts to relock the mutex will cause deadlock. If a thread performs the unlock operation on unlocked or unlocked mutex objects, the result is unknown.

If the mutex type is pthread_mutex_errorcheck, an error check is performed. If a thread attempts to relock a locked mutex, an error is returned. If a thread performs the unlock operation on unlocked or unlocked mutex objects, an error is returned.

If the mutex type is pthread_mutex_recursive, mutex has a lock count concept. When a thread successfully locks a mutex for the first time, the lock count is set to 1. Each time a thread unlocks the mutex, the lock count is used) minus 1. When the lock count is reduced to 0, other threads can obtain the mutex lock. If a thread performs the unlock operation on unlocked or unlocked mutex objects, an error is returned.

If the mutex type is pthread_mutex_default, it is uncertain to obtain the mutex lock recursively. The result of unlock mutex, which is not locked by the call thread, is also uncertain. An attempt to unlock an unlocked mutex results in uncertain results.

Pthread_mutex_trylock () is returned immediately when the mutex object specified by the mutex parameter is locked. In addition, pthread_mutex_trylock () and pthread_mutex_lock () functions exactly the same.

The pthread_mutex_unlock () function releases a lock for the mutex object specified by the mutex parameter. If the object is released, it depends on the type attribute of the mutex object. If multiple threads block the mutex lock to obtain it, calling pthread_mutex_unlock () will make the mutex available. A certain scheduling policy will be used to determine which thread can obtain the mutex lock. (When the mutex type is pthread_mutex_recursive, only when the lock count is reduced to 0 and the call thread has no lock on the mutex) (translated here, I think how vague this lock concept is.) If a thread receives a signal while waiting for a mutex lock, when the return from the signal handler, the thread continues to wait for the mutex lock, just as the thread is not interrupted.

Return Value successful

Pthread_mutex_lock () and pthread_mutex_unlock () return 0; otherwise, an error code is returned.

Pthread_mutex_trylock () returns 0 after a mutex lock is obtained. Otherwise, an error code error is returned.

When pthread_mutex_lock () and pthread_mutex_unlock () fail, [einval] When mutex is generated, the value of its Protocol attribute is pthread_prio_protect, and the priority of the calling thread (priority) higher than the current prority of the mutex

The pthread_mutex_trylock () function fails in the following situations:

[Ebusy] The mutex cocould not be acquired because it was already locked. When mutex is locked, the lock cannot be obtained.

The pthread_mutex_lock (), pthread_mutex_trylock () and pthread_mutex_unlock () functions may fail if:

[Einval] The mutex to which mutex points is not initialized

[Eagain] the lock count (number of locks) of mutex has exceeded the maximum value of recursive cable, and the mutex lock cannot be obtained again.

The pthread_mutex_lock () function will fail in the following circumstances:

[Edeadlk] The current thread has obtained the mutex lock.

The pthread_mutex_unlock () function fails in the following situations:

[Eperm] The current thread is not the owner of the mutex lock. The returned values of these functions are not [eintr].

Mutex lock

Mutex lock is used to ensure that only one thread is executing a piece of code within a period of time. Necessity is obvious: assuming that each thread writes data to the same file in sequence, the final result must be disastrous.

Let's take a look at the following code. This is a read/write program. They share a buffer zone, and we assume that a buffer zone can only save one piece of information. That is, the buffer has only two States: information or no information.

Void reader_function (void );
Void writer_function (void );

Char buffer;
Int buffer_has_item = 0;
Pthread_mutex_t mutex;
Struct timespec delay;
Void main (void ){
Pthread_t reader;
/* Define the latency */
Delay. TV _sec = 2;
Delay. TV _nec = 0;
/* Use the default attribute to initialize a mutex lock object */
Pthread_mutex_init (& mutex, null );
Pthread_create (& reader, pthread_attr_default, (void *) & reader_function), null );
Writer_function ();
}

Void writer_function (void ){
While (1 ){
/* Lock the mutex lock */
Pthread_mutex_lock (& mutex );
If (buffer_has_item = 0 ){
Buffer = make_new_item ();
Buffer_has_item = 1;
}
/* Open the mutex lock */
Pthread_mutex_unlock (& mutex );
Pthread_delay_np (& delay );
}
}

Void reader_function (void ){
While (1 ){
Pthread_mutex_lock (& mutex );
If (buffer_has_item = 1 ){
Consume_item (buffer );
Buffer_has_item = 0;
}
Pthread_mutex_unlock (& mutex );
Pthread_delay_np (& delay );
}
}


The mutex variable mutex is declared here. The structure pthread_mutex_t is an undisclosed data type, which contains an attribute object allocated by the system. The pthread_mutex_init function is used to generate a mutex lock. The null parameter indicates that the default attribute is used. To declare a mutex lock for a specific attribute, call the pthread_mutexattr_init function. The pthread_mutexattr_setpshared function and the pthread_mutexattr_settype function are used to set the mutex lock attribute. The previous function sets the property pshared, which has two values: pthread_process_private and pthread_process_shared. The former is used to synchronize threads in different processes, and the latter is used to synchronize different threads in the local process. In the preceding example, we use the default pthread_process _ private attribute. The latter is used to set mutex lock types. Optional types include pthread_mutex_normal, pthread_mutex_errorcheck, pthread_mutex_recursive, and pthread _ mutex_default. They define different on-board and unlock mechanisms. Generally, the last default attribute is used.

The pthread_mutex_lock statement starts to lock with mutex lock. Subsequent code is locked until pthread_mutex_unlock is called, that is, only one thread can call and execute the lock at a time. When a thread executes at pthread_mutex_lock, if the lock is used by another thread at this time, the thread is blocked, that is, the program will wait until another thread releases the mutex lock. In the above example, we used the pthread_delay_np function to sleep the thread for a period of time to prevent a thread from occupying this function.

The above example is very simple and I will not introduce it any more. It is suggested that a deadlock may occur when mutex lock is used: two threads try to occupy two resources at the same time, and lock the corresponding mutual lock in different order. For example, both threads need to lock mutex lock 1 and mutex lock 2. Thread a First locks mutex lock 1, line B First locks mutex 2, and a deadlock occurs. In this case, we can use the function pthread_mutex_trylock, which is a non-blocking version of the function pthread_mutex_lock. When it finds a deadlock inevitable, it will return the corresponding message, programmers can handle deadlocks accordingly. In addition, different mutex lock types have different deadlocks, but the most important thing is that programmers should pay attention to this in programming.

Introduction to attributes of pthread_mutex_lock ()

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.