【转】pthread mutex 基本用法
轉自:pthread mutex 基本用法 | feng 言 feng 語
鎖是程序中經常需要用到的機制,尤其是多線程的程序中,如果沒有鎖的幫助,線程間的同
步就會非常麻煩甚至不可能。pthread中提供了mutex互斥量這種鎖,在 linux 下經常
用到,以下是pthread_mutex_t的相關函數介紹及簡單用法。
相關函數
| 1 2 3 4 5 6 7 8 9 10 | #include <pthread.h>pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int pthread_mutex_init(pthread_mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr); int pthread_mutex_destroy(pthread_mutex_t *mutex);int pthread_mutex_lock(pthread_mutex_t *mutex); int pthread_mutex_trylock(pthread_mutex_t *mutex); int pthread_mutex_unlock(pthread_mutex_t *mutex); |
使用方法
使用mutex的基本步驟就是:
定義muutex?-> 初始化mutex?-> 使用mutex(lock, unlock, trylock) -> 銷毀mutex。
函數名也已經把它自己的功能描述的非常清楚了。只是有一些細節需要注意:
pthread_mutex_t的初始化有兩種方法,一種是使用函數pthread_mutex_init,使用結
束需要調用函數pthread_mutex_destroy進行銷毀,調用時mutex必須未上鎖。
It shall be safe to destroy an initialized mutex that is unlocked. Attempting
to destroy a locked mutex or a mutex that is referenced (for example, while
being used in a pthread_cond_timedwait() or pthread_cond_wait()) by another
thread results in undefined behavior.
– man pthread_thread_destroy
大意是如果mutex是上鎖狀態,或者被pthread_cond_timedwait()或pthread_cond_wait()
函數引用,此時對其調用pthread_mutex_destroy()結果未定義。
第二種方法是使用PTHREAD_MUTEX_INITIALIZER。根據[1]中的描述,似乎對使用這種方法
初始化的mutex調用pthread_mutex_destroy()會產生錯誤,對未上鎖的mutex調用
pthread_mutex_unlock也會產生錯誤。
Mutex initialization using the PTHREAD_MUTEX_INITIALIZER does not immediately
initialize the mutex. Instead, on first use, pthread_mutex_lock() or
pthread_mutex_trylock() branches into a slow path and causes the
initialization of the mutex. Because a mutex is not just a simple memory
object and requires that some resources be allocated by the system, an attempt
to call pthread_mutex_destroy() or pthread_mutex_unlock() on a mutex that has
statically initialized using PTHREAD_MUTEX_INITIALER and was not yet locked
causes an EINVAL error.
但并沒有找到太多佐證,也不知道這個系統與 Linux 上的實現是否相同。
例子程序
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | #include <stdio.h> #include <pthread.h>/* pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; */ pthread_mutex_t mutex;int count;void * thread_run(void *arg) {int i;pthread_mutex_lock(&mutex);for (i = 0; i < 3; i++) {printf("[%#lx]value of count: %d\n", pthread_self(), ++count);}pthread_mutex_unlock(&mutex);return 0; }int main(int argc, char *argv[]) {pthread_t thread1, thread2;pthread_mutex_init(&mutex, 0);pthread_create(&thread1, NULL, thread_run, 0);pthread_create(&thread2, NULL, thread_run, 0);pthread_join(thread1, 0);pthread_join(thread2, 0);pthread_mutex_destroy(&mutex);return 0; } |
如果使用了第 4 行的初始化方法,可以刪除 23 和 28 行。
Reference
[1]?pthread_mutex_destroy()–Destroy Mutex - IBM Knowledge Center
總結
以上是生活随笔為你收集整理的【转】pthread mutex 基本用法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 下月发布 小米12 Ultra又一重要参
- 下一篇: 微信PC版更新完懵了 找文件竟要经过一串