线程的同步和互斥

多线程共享一个进程的地址空间虽然线程间通信容易进行,但是多线程同时访问共享对象时需要引入同步和互斥机制。
同步指的是多个任务按照约定的顺序相互配合完成一件事情,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;
}

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2012-07-04 21:48  孟浩依然  阅读(9027)  评论(0编辑  收藏  举报