相信自己,只有不想做的,没有做不到的。
分类: LINUX
2013-12-16 21:40:33
POISX互斥锁用pthread_mutex_t描述,主要用来保护临界资源(同一个时刻只能有同一个人访问)
A.定义互斥锁
pthread_mutex_t lock;
B.初始化互斥锁
//动态初始化互斥锁,锁不使用的时候,需要调用pthread_mutex_destroy销毁互斥锁
int pthread_mutex_init(pthread_mutex_t *restrict mutex,
const pthread_mutexattr_t *restrict attr);
//静态初始化互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//销毁互斥锁
int pthread_mutex_destroy(pthread_mutex_t *mutex);
C.获得互斥锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
特点:线程没有获得互斥锁则阻塞
D.释放互斥锁
int pthread_mutex_unlock(pthread_mutex_t *mutex);
五 条件变量
POISX 条件变量描述pthread_cond_t
A.初始化条件变量
int pthread_cond_destroy(pthread_cond_t *cond);
int pthread_cond_init(pthread_cond_t *restrict cond,
const pthread_condattr_t *restrict attr);
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
B.等待条件变量
int pthread_cond_wait(pthread_cond_t *restrict cond,
pthread_mutex_t *restrict mutex);
内部实现:
int pthread_cond_wait(....)
{
1.判断条件是否满足
不满足,释放互斥锁,阻塞调用者
2.条件满足
先获得互斥锁,然后返回
}
条件满足:有其他线程调用pthread_cond_signal或pthread_cond_broadcast时,唤醒等待的线程,条件满足
一般使用:
pthread_mutex_lock(&lock);
pthread_cond_wait(&cond,&lock);
.....
pthread_mutex_unlock(&lock);
练习:(使用互斥锁与条件变量)
1.定义全局buf
2.两个线程,一个线程从键盘向buf输入数据,另一个线程输出buf数据
3.输入"quit",两个线程结束
#include
#include
#include
#include
#include
#include
#include
#include
//全局buffer
char buf[1024];
//定义互斥锁,静态初始化
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *read_thread(void *arg)
{
while(1)
{
pthread_mutex_lock(&lock);
//等待被唤醒
pthread_cond_wait(&cond,&lock);
printf("Read %s from buffer.\n",buf);
if(strncmp(buf,"quit",4) == 0)
break;
pthread_mutex_unlock(&lock);
}
pthread_exit(NULL);
}
void *write_thread(void *arg)
{
while(1)
{
//让读线程先等待
usleep(500);
pthread_mutex_lock(&lock);
printf(">");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf) - 1] = '\0';
pthread_mutex_unlock(&lock);
//唤醒等待的线程
//有效:必须有对应的线程已经处于等待
pthread_cond_signal(&cond);
if(strncmp(buf,"quit",4) == 0)
break;
}
pthread_exit(NULL);
}
//./a.out
int main(int argc, const char *argv[])
{
int ret;
int fd;
pthread_t tid[2];
ret = pthread_create(&tid[0],NULL,read_thread,NULL);
if(ret != 0){
perror("Fail to pthread_create");
exit(EXIT_FAILURE);
}
ret = pthread_create(&tid[1],NULL,write_thread,NULL);
if(ret != 0){
perror("Fail to pthread_create");
exit(EXIT_FAILURE);
}
pthread_join(tid[0],NULL);
pthread_join(tid[1],NULL);
exit(EXIT_SUCCESS);
}