Linux下多線程編程之互斥鎖、條件變量、信號量

一、進程建立函數

 int pthread_create (pthread_t * thread_id, __const pthread_attr_t * __attr, void *(*__start_routine) (void *), void *__restrict __arg);post

第一個參數爲指向線程標識符的指針,第二個參數用來設置線程屬性,第三個參數是線程運行函數的起始地址,最後一個參數是運行函數的參數。spa

一個實例:線程

void *producer(void *args);指針

pthread_t tha;rest

pthread_create(&tha,NULL,producer,NULL);進程

pthread_join(tha,NULL);同步

二、互斥鎖it

經過鎖機制實現線程間的同步。同一時刻只容許一個線程執行一個關鍵部分的代碼。class

int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

一個實例:

pthread_mutex_t lock;

pthread_mutex_init(&lock,NULL);

pthread_mutex_lock(&lock);

臨界區

pthread_mutex_unlock(&lock);

三、條件變量

利用線程間共享的全局變量進行同步的一種機制,一般與互斥鎖一塊兒使用。

int pthread_cond_wait(pthread_cond_t *cond,pthread_mutex_t *mutex); //該函數要在mutex的鎖定區域內使用

int pthread_cond_signal(pthread_cond_t *cond);

一個實例:

pthread_cond_t notfull;

pthread_mutex_lock(&lock);

pthread_cond_wait(&notfull,&lock);

pthread_mutex_unlock(&lock);

四、信號量

#include <semaphore.h>
int sem_init(sem_t *sem , int pshared, unsigned int value);

int sem_wait(sem_t *sem); //給信號量減1,對一個值爲0的信號量調用sem_wait,這個函數將會等待直到有其它線程使它再也不是0爲止。
int sem_post(sem_t *sem); //給信號量的值加1

int sem_destroy(sem_t *sem);

一個實例:

sem_t empty;

sem_t occupied;  //這兩個變量是全局變量

sem_wait(&empty);

...

sem_post(&occupied);

相關文章
相關標籤/搜索