乐闻世界logo
搜索文章和话题

How do you declare a recursive mutex with POSIX threads?

1个答案

1

In POSIX threads (pthread) programming, a recursive mutex is a special type of mutex that allows the same thread to acquire the same lock multiple times. This is particularly useful for recursive functions or when multiple accesses to shared resources are required. To create a recursive mutex, you need to set the mutex attributes using pthread_mutexattr_t and then initialize the mutex with these attributes.

Here are the steps to use a recursive mutex:

Step 1: Initialize Mutex Attributes

First, declare and initialize the pthread_mutexattr_t structure for mutex attributes. Use the pthread_mutexattr_init function to initialize.

c
pthread_mutexattr_t attr; int ret; ret = pthread_mutexattr_init(&attr); if (ret != 0) { perror("Init mutex attribute failed"); // Handle error }

Step 2: Set Mutex Attributes to Recursive

Use the pthread_mutexattr_settype function to set the mutex type to PTHREAD_MUTEX_RECURSIVE.

c
ret = pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); if (ret != 0) { perror("Set attribute type failed"); // Handle error }

Step 3: Initialize the Mutex

Initialize the mutex pthread_mutex_t using the attributes set above.

c
pthread_mutex_t mutex; ret = pthread_mutex_init(&mutex, &attr); if (ret != 0) { perror("Mutex init failed"); // Handle error }

Step 4: Use the Mutex

Now that the mutex is initialized as recursive, it can be safely locked and unlocked multiple times.

c
void recursive_function(int depth) { pthread_mutex_lock(&mutex); if (depth > 0) { printf("Depth: %d\n", depth); recursive_function(depth - 1); } pthread_mutex_unlock(&mutex); } // Call this in some thread recursive_function(5);

Step 5: Clean Up Resources

After using the mutex, destroy the mutex and its attributes.

c
pthread_mutex_destroy(&mutex); pthread_mutexattr_destroy(&attr);

In summary, by setting the mutex attributes to PTHREAD_MUTEX_RECURSIVE, we can create a recursive mutex suitable for recursive function calls. This prevents deadlocks that could occur if the same thread attempts to reacquire a locked mutex.

2024年7月4日 10:34 回复

你的答案