歡迎您光臨本站 註冊首頁

Linux內核同步,進程,線程同步

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
包括我自己在內,很多人對內核,進程,線程同步都不是很清楚,下面稍微總結一下:
內核同步:
主要是防止多核處理器同時訪問修改某段代碼,或者在對設備驅動程序進行臨界區保護.主要有一下幾種方式:
1. Mutex(互斥)
頭文件:
#include <linux/mutex.h>
初始化方法:
DEFINE_MUTEX(name);或者
void mutex_init(struct mutex *lock);
使用方法:
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);


[火星人 ] Linux內核同步,進程,線程同步已經有1110次圍觀

http://coctec.com/docs/linux/show-post-53712.html