void mutex_lock (struct mutex *lock); Tries to lock the mutex, sleeps otherwise. Caution: can't be interrupted, resulting in processes you cannot kill!
int mutex_lock_interruptible (struct mutex *lock); Same, but can be interrupted. If interrupted, returns a non zero value and doesn't hold the lock. Test the return value!!!
int mutex_trylock (struct mutex *lock); Never waits. Returns a non zero value if the mutex is not available.int mutex_is_locked(struct mutex *lock);Just tells whether the mutex is locked or not.
void mutex_unlock (struct mutex *lock); Releases the lock. Make sure you do it as quickly as possible!
2. Reader/writer semphopres 讀寫信號量
Allow shared access by unlimited readers, or by only 1 writer. Writers get priority.
允許有限數量的讀訪問,但是只能有一個寫訪問. void init_rwsem (struct rw_semaphore *sem); void down_read (struct rw_semaphore *sem); int down_read_trylock (struct rw_semaphore *sem); int up_read (struct rw_semaphore *sem); void down_write (struct rw_semaphore *sem); int down_write_trylock (struct rw_semaphore *sem); int up_write (struct rw_semaphore *sem); Well suited for rare writes, holding the semaphore briefly. Otherwise, readers get starved, waiting too long for the semaphore to be released.
線程同步
1. semophore 信號量
簡單用法:
#include <semaphore.h>
sem_t bin_sem;
res = sem_init(&bin_sem, 0, 0);
sem_wait(&bin_sem);
sem_post(&bin_sem);
sem_destroy(&bin_sem);
2. Mutex 互斥
頭文件以及函數
#include <pthread.h> int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr); int pthread_mutex_lock(pthread_mutex_t *mutex)); int pthread_mutex_unlock(pthread_mutex_t *mutex); int pthread_mutex_destroy(pthread_mutex_t *mutex);