Usage of mutex and condtion for Thread Synchronization in Android

Source: Internet
Author: User
Tian haili
2013-08-10

Android-encapsulated synchronization classes mainly include mutex (automutex) and condition. This article analyzes how to use them. For specific implementation, see implementation of mutex and condtion for Thread Synchronization in Android and usage of mutex and condition for pthread.
Keywords: mutex, condition variable, autolock/automutex, Android
Keywords: mutex, condition variable, automatic lock/automatic mutex, Android

1. mutex

View mutex's external interface definition (declared in frameworks/native/include/utils/mutex. h)
<Figure 1 todo>

1.1 Structure/Analysis
Mutex();Mutex(const char* name);Mutex(int type, const char* name = NULL);~Mutex();

The difference between constructors is that parameters:
-Name indicates the mutex name. If this parameter is not specified, the default value is null;
-Type indicates the mutex type.

    enum {        PRIVATE = 0,        SHARED = 1    };

Two types: Private is used inside the process; shared is applicable to cross-process sharing.
If this parameter is not specified, the default value is private.

1.2 Function

Mutex has the following functions:

    status_t    lock();    void        unlock();    status_t    tryLock();

Lock () to obtain the lock. If it is obtained, return; otherwise, wait;
Unlock () releases the lock;
Trylock () if the current lock can be obtained (not obtained by other threads), it will be locked; otherwise, it will be returned directly. Return Value: 0 indicates success; other values fail. The difference between lock () and lock () is that the system returns results in a timely manner regardless of the success or failure, rather than waiting.

The thread acquires the lock through lock () before entering the mutex protection critical section. After obtaining the lock, it can execute the code in the critical section and release the lock through unlock after exiting the critical section.
At a certain time, at most one thread is executing in the critical section. If the existing thread T1 is executing, the other thread T2 to enter the critical section will be suspended and waiting after the thread T2; after thread T1 releases the lock, thread T2 can obtain the lock and enter the critical section for execution.

Lock ()/unlock () must be used together. trylock () selects whether to unlock () based on whether the lock is obtained based on the execution result ().

1.3 typical scenarios
M_mutex.lock (); // critical area, the content to be protected m_mutex.unlock ();

Ii. Condition

Check the external interface definition of condition (declared in frameworks/native/include/utils/condition. h)
<Figure 2 todo>

2.1 Structure/Analysis
    Condition();    Condition(int type);    ~Condition();

The difference between constructors is that the type parameter:
-Type indicates the condition type.

    enum {        PRIVATE = 0,        SHARED = 1    };

Two types: Private is used inside the process; shared is applicable to cross-process sharing.
If this parameter is not specified, the default value is private.

2.2 Function

Condition has the following four main functions:

    status_t wait(Mutex& mutex);    status_t waitRelative(Mutex& mutex, nsecs_t reltime);    void signal();    void broadcast();

Wait () Waiting condition variable (condition variable)
Mutex is used as a parameter. Before calling this function, the mutex must be locked.
Executing this function will unlock the mutex and wait for the conditional variable. If the conditional variable cannot be obtained, it will be suspended for waiting. If the conditional variable is obtained, the mutex will be locked again and returned. These operations are atomic operations.
After the function is executed, mutex is locked again. Therefore, after the function is executed, the mutex unlock operation is required.
The difference between waitrelative () and wait () is that there will be a wait timeout time, and when the time does not get the conditional variable, it will return, you can judge the result through the return value.
Signal () and broadcast () trigger conditional variable (condition variable)
The difference between signal () and broadcast () Is that signal () can only be obtained by a thread waiting for the conditional variable; broadcast () allow all threads waiting for the condition variable to obtain and continue execution.
Signal () and broadcast () must also lock the mutex before execution, and then unlock the mutex.

2.3 typical scenarios

Execution of thread T1:

m_mutex.lock();   m_cond.wait(m_mutex);   m_mutex.unlock();

Thread T1 waits for a condition to be met through a condition variable.

Thread T2 execution:

m_mutex.lock();   m_cond.signal();   m_mutex.unlock();

After the condition is met, thread T2.

Iii. autolock/automutex

Autolock is defined to simplify the use of mutex. It is also defined in frameworks/native/include/utils/mutex. h encapsulates mutex and uses the structure and structure of C ++.

        Autolock(Mutex& mutex);        Autolock(Mutex* mutex);        ~Autolock();

The usage is very simple. to define a local temporary automutex variable, where the variable is defined, the constructor is automatically called and the mutex lock () operation is executed; at the end of the scope of the variable, the Destructor is automatically called and the mutex unlock operation is executed.
Therefore, you can define an automutex variable at the beginning of the mutex protection area to implement mutex protection for this area.

Iv. Summary

This article briefly introduces the commonly used synchronization mechanisms mutex (automutex) and condition in Android. Subsequent articles (implementation of mutex and condtion in thread synchronization in Android and usage of mutex and condition in pthread) will show how they are implemented.

Related Article

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.