Implement the C code for the mutex lock and unlock operations in Linux.

Source: Internet
Author: User

Implement the C code for the mutex lock and unlock operations in Linux.

I. Overview
In actual software programs, the calling relationship between functions is complicated due to the large amount of code. Therefore, you must be extremely careful when performing operations on certain global variables. In programs, mutex lock is generally used to ensure the uniqueness of operations on global variables.
This article describes in detail the C code implementation of the mutex lock and unlock operations in Linux, which provides a useful reference for the development of related software.

II. Introduction to locking and unlocking functions and time Structures
1. locking function pthread_mutex_timedlock
Function prototype: int pthread_mutex_timedlock (pthread_mutex_t * restrict mutex, const struct timespec * restrict abstime );
Function Description: The pthread_mutex_timedlock function is used to lock mutex. If the mutex is locked, the function waits until the mutex is unlocked and the waiting time is specified by abstime.
Function return value: 0 indicates that the lock is successful, and other values indicate that the lock fails.

2. Unlock function pthread_mutex_unlock
Function prototype: int pthread_mutex_unlock (pthread_mutex_t * mutex );
Function Description: The pthread_mutex_unlock function is used to release mutex.
Function return value: 0 indicates that the lock is successful, and other values indicate that the lock fails.

3. timespec struct

struct timespec{    time_t  tv_sec;    /*second*/    long    tv_nsec;   /*nanosecond*/}

The struct has two member variables: TV _sec indicates seconds, and TV _nsec indicates nanoseconds.

4. timeval struct

struct timeval{    time_t      tv_sec;     /*seconds*/    suseconds   tv_usec;    /*microseconds*/}

The struct has two member variables: TV _sec indicates seconds, and TV _usec indicates microseconds.

III. C program implementation
This program is named "LockAndUnlock. c", where "MutexLock" is the locking function and "MutexUnLock" is the unlocking function.
The Code is as follows:

/*************************************** * ******************************** All Rights Reserved (C) 2015, Zhou Zhaoxiong. ** File name: LockAndUnlock. c * File ID: none * Content Abstract: demonstrate the call of the lock and unlock function * Other Instructions: none * Current version: V1.0 * Author: Zhou Zhaoxiong * completion date: 20150509 *************************************** * *******************************/# include <sys/time. h> # include <pthread. h> // macro definition # define LOCKTIMEOUT 5000 // The mutex timeout duration is 5000 milliseconds // global variable pthread_mutex_t g_Mutex; // redefine the Data Type typedef signed int INT32; // function declaration INT32 MutexLock (); INT32 MutexUnLock (); INT32 main ();/*********** **************************************** * ******************** Function description: main function * input parameter: none * output parameter: none * return value: none * Other description: no * modified date version number modifier modified content * found * 20150509 V1.0 Zhou Zhaoxiong create *********************** **************************************** * *******/INT32 main () {INT32 iRetCode = 0; iRetCode = MutexLock (); // lock the mutex if (iRetCode <0) {printf ("exec MutexLock Failed! \ N "); return-1;} printf (" -------------- \ n "); printf (" Add code here! \ N "); printf (" -------------- \ n "); iRetCode = MutexUnLock (); // mutex unlock if (iRetCode <0) {printf (" exec MutexUnLock failed! \ N "); return-1;} return 0 ;} /*************************************** * ******************************** function description: mutex lock * input parameter: none * output parameter: none * return value: 0-success-1-failure * Other Instructions: no * modified date version number modifier modified content * found * 20150509 V1.0 Zhou Zhaoxiong create *********************** **************************************** * ***/INT32 MutexLock () {struct timeval tCurrentTime; stru Ct timespec tTimeout; INT32 iRetCode = 0; gettimeofday (& tCurrentTime, NULL); // obtain the current absolute time tTimeout. TV _sec = tCurrentTime. TV _sec + LOCKTIMEOUT/1000; // specify the timeout value tTimeout. TV _nsec = tCurrentTime. TV _usec * 1000; iRetCode = pthread_mutex_timedlock (& g_Mutex, & tTimeout); if (iRetCode! = 0) {printf ("MutexLock: exec pthread_mutex_timedlock failed, RetCode = % d \ n", iRetCode); return-1;} return 0 ;} /*************************************** * ******************************** function description: unlock mutex * input parameter: none * output parameter: none * return value: none * Other Instructions: no * modified date version number modifier modified content * found * 20150509 V1.0 Zhou Zhaoxiong create *********************** ************************* * *****************/INT32 MutexUnLock () {INT32 iRetCode = 0; iRetCode = pthread_mutex_unlock (& g_Mutex ); if (iRetCode! = 0) {printf ("MutexUnLock: exec pthread_mutex_unlock failed, RetCode = % d \ n", iRetCode); return-1;} return 0 ;}

Iv. File compilation and running results
In Linux, run the "gcc-g-pthread-o LockAndUnlock. c" or "gcc LockAndUnlock. c-o LockAndUnlock-lpthread" command to generate "LockAndUnlock ". Then run the "LockAndUnlock" command. The program running result is as follows:

--------------Add code here!--------------

V. Summary
This article provides the C code implementation of the mutex lock and unlock operations in Linux. The "MutexLock" and "MutexUnLock" functions in the program can be called as APIS for other programs that require similar operations.

My public account: zhouzxi. Please scan the following QR code:

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.