【基础】函数 mutex_init() / mutex_lock() / mutex_unlock()

本文详细介绍了Linux中互斥锁(Mutex)的初始化、锁定及解锁操作,并强调了Mutex的使用限制,例如不可在中断上下文中使用等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

转自:http://blog.youkuaiyun.com/jgw2008/article/details/52701523

1. 初始化互斥体 -- mutex_init();

2. 获得互斥体 -- mutex_lock();

3. 释放互斥体 -- mutex_unlock();

mutex不能使用在 中断的上下文 中。



1. mutex_init(), 注意mutex使用之前都需要先init

  1. /**  
  2.  * mutex_init - initialize the mutex  
  3.  * @mutex: the mutex to be initialized  
  4.  *  
  5.  * Initialize the mutex to unlocked state.  
  6.  *  
  7.  * It is not allowed to initialize an already locked mutex.  
  8.  */  
  9. # define mutex_init(mutex) \  
  10. do {                            \  
  11.     static struct lock_class_key __key;     \  
  12.                             \  
  13.     __mutex_init((mutex), #mutex, &__key);      \  
  14. } while (0)  

  1. void  
  2. __mutex_init(struct mutex *lock, const char *name, struct lock_class_key *key)  
  3. {  
  4.     atomic_set(&lock->count, 1);  
  5.     spin_lock_init(&lock->wait_lock);  
  6.     INIT_LIST_HEAD(&lock->wait_list);  
  7.     mutex_clear_owner(lock);  
  8. #ifdef CONFIG_MUTEX_SPIN_ON_OWNER  
  9.     lock->spin_mlock = NULL;  
  10. #endif  
  11.   
  12.     debug_mutex_init(lock, name, key);  
  13. }  


2. mutex_lock(), 注意看注释说明,

a. 如果mutex已经被其他task获取,那么目前的task先sleep直到获取;

b. mutex不能被嵌套获取;上一个task释放mutex之后,才能被其他的task获取;

c. mutex要先被初始化才能使用;mutex正在使用过程中,其内存不能被释放;

  1. /**  
  2.  * mutex_lock - acquire the mutex  
  3.  * @lock: the mutex to be acquired  
  4.  *  
  5.  * Lock the mutex exclusively for this task. If the mutex is not  
  6.  * available right now, it will sleep until it can get it.  
  7.  *  
  8.  * The mutex must later on be released by the same task that  
  9.  * acquired it. Recursive locking is not allowed. The task  
  10.  * may not exit without first unlocking the mutex. Also, kernel  
  11.  * memory where the mutex resides mutex must not be freed with  
  12.  * the mutex still locked. The mutex must first be initialized  
  13.  * (or statically defined) before it can be locked. memset()-ing  
  14.  * the mutex to 0 is not allowed.  
  15.  *  
  16.  * ( The CONFIG_DEBUG_MUTEXES .config option turns on debugging  
  17.  *   checks that will enforce the restrictions and will also do  
  18.  *   deadlock debugging. )  
  19.  *  
  20.  * This function is similar to (but not equivalent to) down().  
  21.  */  
  22. void __sched mutex_lock(struct mutex *lock)  
  23. {  
  24.     might_sleep();  
  25.     /*  
  26.      * The locking fastpath is the 1->0 transition from  
  27.      * 'unlocked' into 'locked' state.  
  28.      */  
  29.     __mutex_fastpath_lock(&lock->count, __mutex_lock_slowpath);  
  30.     mutex_set_owner(lock);  
  31. }  


3. mutex_unlock(), 释放互斥体

a. 释放之前获得的mutex;

b. mutex只有被获得,才能调用这个函数来释放;换言之,如果没有获得,就没有必要做释放的动作;

  1. /**  
  2.  * mutex_unlock - release the mutex  
  3.  * @lock: the mutex to be released  
  4.  *  
  5.  * Unlock a mutex that has been locked by this task previously.  
  6.  *  
  7.  * This function must not be used in interrupt context. Unlocking  
  8.  * of a not locked mutex is not allowed.  
  9.  *  
  10.  * This function is similar to (but not equivalent to) up().  
  11.  */  
  12. void __sched mutex_unlock(struct mutex *lock)  
  13. {  
  14.     /*  
  15.      * The unlocking fastpath is the 0->1 transition from 'locked'  
  16.      * into 'unlocked' state:  
  17.      */  
  18. #ifndef CONFIG_DEBUG_MUTEXES  
  19.     /*  
  20.      * When debugging is enabled we must not clear the owner before time,  
  21.      * the slow path will always be taken, and that clears the owner field  
  22.      * after verifying that it was indeed current.  
  23.      */  
  24.     mutex_clear_owner(lock);  
  25. #endif  
  26.     __mutex_fastpath_unlock(&lock->count, __mutex_unlock_slowpath);  

<think>我们正在讨论两个函数:pthread_mutex_init和pthread_create。根据引用内容,pthread_mutex_init用于初始化互斥锁,而pthread_create用于创建新线程。首先,我们分别介绍这两个函数的定义和用途。1.pthread_mutex_init函数用途:初始化一个互斥锁(mutex)。互斥锁用于多线程编程中保护共享资源,防止多个线程同时访问导致的数据竞争问题。函数原型(根据引用[2]):intpthread_mutex_init(pthread_mutex_t*restrictmutex,constpthread_mutexattr_t*restrictattr);参数说明:-mutex:指向要初始化的互斥锁的指针。-attr:指向互斥锁属性的指针。如果为NULL,则使用默认属性。返回值:成功返回0,失败返回错误编号。此外,引用[1]和[2]提到了一种静态初始化方法,使用宏PTHREAD_MUTEX_INITIALIZER:pthread_mutex_tmutex=PTHREAD_MUTEX_INITIALIZER;这种方法在定义互斥锁变量的同时进行初始化,无需调用pthread_mutex_init函数。但注意,静态初始化只能用于全局或静态的互斥锁,且不能设置属性。引用[4]中提到,如果使用静态初始化(即使用宏)的方式,那么即使没有调用pthread_mutex_init,互斥锁也是生效的。2.pthread_create函数用途:创建一个新的线程。新线程执行指定的函数函数原型(根据引用[3]):intpthread_create(pthread_t*restricttidp,constpthread_attr_t*restrictattr,void*(*start_rtn)(void*),void*restrictarg);参数说明:-tidp:指向线程标识符的指针,用于存储新线程的ID。-attr:指向线程属性的指针。如果为NULL,则使用默认属性。-start_rtn:线程要执行的函数指针,该函数接受一个void*参数并返回void*。-arg:传递给线程函数的参数。返回值:成功返回0,失败返回错误编号。下面我们给出一个示例,展示如何使用这两个函数:-首先静态初始化一个互斥锁(也可以使用pthread_mutex_init动态初始化)。-然后创建两个线程,这两个线程都会尝试获取同一个互斥锁,然后对共享资源进行操作。注意:在多线程编程中,使用互斥锁保护共享资源是必要的,以避免数据竞争。示例代码:*/#include<stdio.h>#include<pthread.h>//静态初始化互斥锁pthread_mutex_tmutex=PTHREAD_MUTEX_INITIALIZER;//共享资源intshared_counter=0;//线程函数void*increment_counter(void*arg){inti;for(i=0;i<100000;i++){//加锁pthread_mutex_lock(&mutex);shared_counter++;//解锁pthread_mutex_unlock(&mutex);}returnNULL;}intmain(){pthread_tthread1,thread2;//创建线程1if(pthread_create(&thread1,NULL,increment_counter,NULL)){fprintf(stderr,"Errorcreatingthread1\n");return1;}//创建线程2if(pthread_create(&thread2,NULL,increment_counter,NULL)){fprintf(stderr,"Errorcreatingthread2\n");return1;}//等待线程结束pthread_join(thread1,NULL);pthread_join(thread2,NULL);printf("Sharedcountervalue:%d\n",shared_counter);//预期为200000return0;}/*在这个例子中,两个线程分别对共享变量shared_counter增加100000次,由于互斥锁的保护,最终结果会是200000。如果没有互斥锁,结果可能会小于200000。总结:-pthread_mutex_init:用于初始化互斥锁(动态初始化),或者使用宏PTHREAD_MUTEX_INITIALIZER进行静态初始化[^1][^2][^4]。-pthread_create:用于创建新线程,指定线程要执行的函数和参数[^3]。注意:使用完互斥锁后,需要调用pthread_mutex_destroy销毁互斥锁(对于动态初始化的互斥锁)。但在上面的静态初始化例子中,不需要销毁,因为静态初始化的互斥锁在程序结束时自动释放。如果使用动态初始化,则需要在不再使用互斥锁时销毁:pthread_mutex_destroy(&mutex);另外,在创建线程时,需要注意线程函数的签名:它必须是一个返回void*且参数为void*的函数。最后,我们生成几个相关问题:*/</think>### `pthread_mutex_init` 和 `pthread_create` 函数详解 #### 一、`pthread_mutex_init` - 互斥锁初始化 **用途**:初始化互斥锁(Mutex),用于多线程同步,防止多个线程同时访问共享资源导致数据竞争[^1][^2]。 **函数原型**: ```c int pthread_mutex_init( pthread_mutex_t *restrict mutex, // 指向互斥锁的指针 const pthread_mutexattr_t *restrict attr // 锁属性(NULL表示默认属性) ); ``` **两种初始化方式**: 1. **动态初始化**(运行时初始化): ```c pthread_mutex_t my_mutex; pthread_mutex_init(&my_mutex, NULL); // 显式初始化[^2] ``` 2. **静态初始化**(编译时初始化): ```c pthread_mutex_t my_mutex = PTHREAD_MUTEX_INITIALIZER; // 宏赋值即完成初始化[^1][^4] ``` **关键特性**: - 静态初始化无需显式调用 `pthread_mutex_init`[^4] - 使用后需销毁锁:`pthread_mutex_destroy(&my_mutex)` - 基础操作: ```c pthread_mutex_lock(&my_mutex); // 加锁 pthread_mutex_unlock(&my_mutex); // 解锁 ``` #### 二、`pthread_create` - 线程创建 **用途**:创建新的POSIX线程(pthread),实现并发执行[^3]。 **函数原型**: ```c int pthread_create( pthread_t *restrict tidp, // 存储新线程ID const pthread_attr_t *restrict attr, // 线程属性(NULL表示默认) void *(*start_rtn)(void *), // 线程函数指针 void *restrict arg // 传递给线程函数的参数 ); ``` **参数解析**: | 参数 | 说明 | |-------------|----------------------------------------------------------------------| | `tidp` | 输出参数,返回新线程的ID | | `attr` | 线程属性(栈大小、调度策略等),NULL表示默认属性 | | `start_rtn` | 线程入口函数,格式:`void* thread_func(void *arg)` | | `arg` | 传递给`start_rtn`的参数,可以是任意类型指针 | **返回值**:成功返回0,失败返回错误码(非0)。 #### 三、联合使用示例 ```c #include <pthread.h> #include <stdio.h> pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER; // 静态初始化锁[^1] int shared_counter = 0; // 线程函数 void* increment_counter(void* arg) { for(int i = 0; i < 10000; i++) { pthread_mutex_lock(&counter_mutex); // 加锁 shared_counter++; // 临界区操作 pthread_mutex_unlock(&counter_mutex);// 解锁 } return NULL; } int main() { pthread_t thread1, thread2; // 创建线程1 pthread_create(&thread1, NULL, increment_counter, NULL); // [^3] // 创建线程2 pthread_create(&thread2, NULL, increment_counter, NULL); pthread_join(thread1, NULL); // 等待线程结束 pthread_join(thread2, NULL); printf("Final counter: %d\n", shared_counter); // 正确输出20000 pthread_mutex_destroy(&counter_mutex); // 销毁锁 return 0; } ``` > 此例展示: > 1. 静态初始化互斥锁(无需显式调用`pthread_mutex_init`)[^4] > 2. 创建两个线程并发执行 > 3. 通过互斥锁保护共享变量`shared_counter` #### 四、关键区别总结 | **特性** | `pthread_mutex_init` | `pthread_create` | |-------------------|------------------------------------------|---------------------------------------| | 作用对象 | 互斥锁(同步原语) | 线程(执行单元) | | 初始化必要性 | 必须初始化后才能使用锁操作 | 必须调用才能创建新线程 | | 静态初始化支持 | 支持(`PTHREAD_MUTEX_INITIALIZER`)[^1] | 不支持 | | 资源释放 | 需要`pthread_mutex_destroy` | 需要`pthread_join`或`pthread_detach` | | 典型使用场景 | 保护临界区 | 实现并发任务 | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值