Linux C mutex mutex usage record

Source: Internet
Author: User

One, mutex mutex mainly contains a few functions:

1, int pthread_mutex_init (pthread_mutex_t *mutex, const pthread_mutexattr_t *attr);

Initializes a mutex, and if attr is NULL, the default value is initialized, and a mutex can be initialized as follows when the mutex is defined:

pthread_mutex_t mutex = Pthread_mutex_initializer;

A lock semaphore that can be restored directly to the initial state without generating an error.

2, int Pthread_mutex_destroy (pthread_mutex_t *mutex);

Destroys a mutex that can be destroyed only if it is idle (without being unlock by lock or lock), destroying a lock's semaphore and generating (16,device or resource busy) error;

The amount of the destroyed semaphore can be re-initialized.

3, int pthread_mutex_lock (pthread_mutex_t *mutex) and int pthread_mutex_trylock (pthread_mutex_t *mutex) and int pthread_ Mutex_timedlock (pthread_mutex_t *mutex,const struct timespec *abstime);

These three functions are similar in that they all lock (get) a mutex mutex, except that pthread_mutex_trylock non-blocking mode functions return immediately, Pthread_mutex_lock and Pthread_mutex_ Timedlock is a blocking mode;

Pthread_mutex_timedlock Timeout wait time abstime is absolute time and can be set as follows:

void set_abswaittime (structint  ms) {

Long sec;
Long usec;
struct Timeval tnow;
Gettimeofday (&tnow, NULL);
USEC = tnow.tv_usec + ms*1000;
SEC = tnow.tv_sec+usec/1000000;
Outtime->tv_nsec= (usec%1000000) *1000;
outtime->tv_sec=sec;

}

4, int pthread_mutex_unlock (pthread_mutex_t *mutex);

Frees a mutex mutex, and if the thread attempts to unlock an unlocked mutex, Pthread_mutex_unlock will follow the table below.

Reference: http://pubs.opengroup.org/onlinepubs/9699919799/functions/pthread_mutex_lock.html#tag_16_439

Linux C mutex mutex usage record

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.