pthread_mutex_init
时间: 2023-09-12 08:13:21 浏览: 107
pthread_mutex
pthread_mutex_init is a function in the POSIX threads library that is used to initialize a mutex. A mutex is a synchronization object that is used to protect critical sections of code so that only one thread can access the critical section at a time.
The function takes three arguments:
1. A pointer to the mutex variable that needs to be initialized.
2. A pointer to a pthread_mutexattr_t structure that contains the mutex attributes. If NULL is passed, default attributes are used.
3. An integer value that specifies the type of mutex. There are three types of mutexes: PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_ERRORCHECK, and PTHREAD_MUTEX_RECURSIVE.
The function returns 0 on success and an error code on failure.
Here's an example of how to use pthread_mutex_init to initialize a mutex:
```
#include <pthread.h>
pthread_mutex_t my_mutex;
int main()
{
int ret;
ret = pthread_mutex_init(&my_mutex, NULL);
if (ret != 0) {
// Handle error
}
// Use the mutex
ret = pthread_mutex_destroy(&my_mutex);
if (ret != 0) {
// Handle error
}
return 0;
}
```
In this example, we declare a pthread_mutex_t variable called my_mutex and initialize it using pthread_mutex_init. We pass NULL for the second argument to use default attributes and PTHREAD_MUTEX_NORMAL for the third argument to create a normal mutex.
After the mutex is initialized, we can use it to protect a critical section of code. Finally, we destroy the mutex using pthread_mutex_destroy.
阅读全文