線程的同步和互斥


多線程共享一個進程的地址空間雖然線程間通信容易進行,但是多線程同時訪問共享對象時需要引入同步和互斥機制。
同步指的是多個任務按照約定的順序相互配合完成一件事情,dijkstra基於信號量的概念提出了一種同步機制。由信號量
賴決定線程是繼續運行還是阻塞等待。

信號量代表某一類資源,其值表示系統中該資源的數量
信號量是一個受保護的變量,智能通過三種操作來訪問:初始化 P操作(申請資源),V操作(釋放資源),信號量的值為非負整數
P操作的含義: if(信號量的值大於0)
{
申請資源的任務繼續運行;
信號量的值減去1;
}
else
{
申請資源的任務阻塞;
}
v操作的含義: if(沒有任務在等待該資源){信號量的值加1;}
else{喚醒第一個等待的任務,讓其繼續運行}

POSIX Semaphore API
posix 中定義了兩類信號量:
無名信號量和有名信號量

pthread庫常用的信號量操作函數如下:

int sem_init(sem_t *sem,int pshared,unsigned int value);
int sem_wait(sem_t *sem); P操作
int sem_post(sem_t * sem);V操作
int sem_trywait(sem_t *sem);
int sem_getvalue(sem_t *sem,int *svalue);

例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <semaphore.h>
char buf[60];
sem_t sem;
void * function(void *arg);
int main()
{
pthread_t a_thread;
void * thread_result;
if(sem_init(&sem,0,0)<0)
{
perror("fail to sem_init");
exit(-1);
}
if(pthread_create(&a_thread,NULL,function,NULL)<0)
{
perror("fail to pthread_create");
exit(-1);
}
printf("input 'quit' to exit\n");
do
{
fgets(buf,60,stdin);
sem_post(&sem);

}while(strncmp(buf,"quit",4)!= 0);
return 0;

}
void * function(void *arg)
{
while(1)
{
sem_wait(&sem);
printf("YOu enter %d characters\n",strlen(buf)-1);
}
}

 

 


線程間的互斥,引入互斥鎖的目的是用來保證共享資源數據操作的完整性。
互斥鎖主要用來保護臨界資源
每個鄰居資源都由一個互斥鎖來保護,任何時刻最多只能有一個線程能訪問該資源。

線程必須先獲得互斥鎖才能訪問臨界資源,訪問完臨界資源后釋放該鎖。如果無法獲得鎖,線程會阻塞知道獲得鎖為止。

初始化互斥鎖
所需頭文件: #include<pthread.h>
函數原型;
int pthread_mutex_init(pthread_mutex_t * mutex,pthread_mutexattr_t *attr);
函數參數:mutex:互斥鎖
attr: 互斥鎖屬性 //NULL表示缺省屬性

函數返回值:成功 0,失敗 -1

申請互斥鎖:
函數原型:
int pthread_mutex_lock(pthread_mutex_t *mutex)
函數參數:
mutex 互斥鎖
成功 0,失敗 -1
釋放互斥鎖:
int pthread_mutex_unlock(pthread_mutex_t * mutex)

成功返回0,失敗-1;

 


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
int value1,value2;

unsigned int count = 0;
pthread_mutex_t mutex;
void * function(void *arg);
int main()
{
pthread_t a_thread;
void * thread_result;

if(pthread_mutex_init(&mutex,NULL) < 0)
{
perror("fail to mutex_init");
exit(-1);
}
if(pthread_create(&a_thread,NULL,function,NULL)<0)
{
perror("fail to pthread_create");
exit(-1);
}
while(1)
{
count++;
#ifdef _LOCK_
pthread_mutex_lock(&mutex);
#endif
value1 = count;
value2 = count;
#ifdef _LOCK_
pthread_mutex_unlock(&mutex);
#endif
}
return 0;
}
void * function(void *arg)
{
while(1)
{
#ifdef _LOCK_
pthread_mutex_lock(&mutex);
#endif
if(value1 != value2)
{
printf("count =%d,value1 =%d,value2=%d\n",count,value1,value2);
}
#ifdef _LOCK_
pthread_mutex_unlock(&mutex);
#endif
}
return NULL;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM