線程互互斥鎖

鎖的實現原理ide

互斥對象的主要操做有兩個加鎖(lock)和釋放鎖(unlock)。當一個線程對互斥對象進行lock操做併成功得到這個互斥對象的全部權,在此線程對此對象unlock前,其餘線程對這個互斥對象的lock操做都會被阻塞函數

舉例: metux m_metux1;線程

thread thread1;
thread thread2;
線程1線對 m_metux1 thread1.lock(m_metux1);獲得互斥對象m_metux1 的全部權
而線程2阻塞在thread2.lock(m_metux1)這裏對象

pthread_mutex_t m_mutex;同步

pthread_mutex_init(&m_mutex, NULL);
pthread_mutex_lock(&m_mutex);
pthread_mutex_unlock(&m_mutex);
pthread_mutex_destroy(&m_mutex);it

在線程實際運行過程當中,咱們常常須要多個線程保持同步。這時能夠用互斥鎖來完成任務;互斥鎖的使用過程當中,主要有pthread_mutex_init,pthread_mutex_destory,pthread_mutex_lock,pthread_mutex_unlock這幾個函數以完成鎖的初始化,鎖的銷燬,上鎖和釋放鎖操做。io

#include <pthread.h>
#include <stdio.h>class

pthread_mutex_t mutex ;
void print_msg(void arg){
int i=0;
pthread_mutex_lock(&mutex);
for(i=0;i<15;i++){
printf("output : %d\n",i);
usleep(100);
}
pthread_mutex_unlock(&mutex);
}
int main(int argc,char** argv){
pthread_t id1;
pthread_t id2;
pthread_mutex_init(&mutex,NULL);
pthread_create(&id1,NULL,print_msg,NULL);
pthread_create(&id2,NULL,print_msg,NULL);
pthread_join(id1,NULL);
pthread_join(id2,NULL);
pthread_mutex_destroy(&mutex);
return 1;thread

相關文章
相關標籤/搜索