Linux多線程同步方法
以下是線程的幾種同步方式:
本文引用地址:http://cafeforensic.com/article/264051.htmlinux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)
1、 互斥量。
通過(guò)使用pthread的互斥接口保護(hù)數(shù)據(jù),確保同一時(shí)間只有一個(gè)線程訪問(wèn)數(shù)據(jù)。互斥量從本質(zhì)上講是一把鎖,在訪問(wèn)共享資源前對(duì)互斥量進(jìn)行加鎖,在訪問(wèn)完成后釋放互斥量上的鎖。如下例所示,就是互斥量對(duì)共享數(shù)據(jù)的操作:
#include
#include
int value = 5;//共享變量
pthread_mutex_t mutex;//互斥變量
void *mythread1();
void mainshow();
int main()
{
int retval;
pthread_t tid1;
retval = pthread_create(&tid1,NULL,mythread1,&value);//創(chuàng)建線程
if(retval != 0){printf(“Can not create mythread1n”);
mainshow();
retval = pthread_join(&tid1,NULL);//等待線程mythread1結(jié)束
if(retval != 0){printf(“Can not join with mythread.n”);
printf(“value = %dn”,value);
return 0;
}
void *mythread1()
{
int retval;
retval = pthread_mutex_lock(&mutex);//上鎖
value = value + 1;//對(duì)共享變量的操作
printf("value = %dn",value);
retval = pthread_mutex_unlock(&mutex);//解鎖
pthread_exit((void *)0);
}
void myshow()
{
int retval;
retval = pthread_mutex_lock(&mutex);//上鎖
value = value + 1;//對(duì)共享變量的操作
printf(“value = %dn”,value);
pthread_mutex_unlock(&mutex);//解鎖
}
2、信號(hào)量
該信號(hào)量是Posix提供的基于內(nèi)存的信號(hào)量,它們由應(yīng)用程序分配信號(hào)量的內(nèi)存空間。如下例所示,就是信號(hào)量對(duì)共享數(shù)據(jù)的操作:
#include
#include
#include
int value = 5;
sem_t sem1,sem2;
void mainshow();
void *mythread();
int main()
{
int retval;
pthread_t tid;
retval = sem_init(&sem1,0,0);
retval = sem_init(&sem2,0,1);
retval =pthread_create(&tid,NULL,mythread,NULL);
mainshow();
pthread_join(tid,NULL);
printf("value3 = %dn",value);
return 0;
}
void *mythread()
{
int retval;
retval = sem_wait(&sem1);
value = value + 1;
printf("value1 = %dn",value);
retval = sem_post(&sem2);
pthread_exit((void *) 0);
}
void mainshow()
{
int retval;
retval = sem_wait(&sem2);
value = value + 1;
printf("value2 = %dn",value);
retval = sem_post(&sem1);
}
linux操作系統(tǒng)文章專題:linux操作系統(tǒng)詳解(linux不再難懂)linux相關(guān)文章:linux教程
評(píng)論