一、互斥锁
在POSIX Thread中定义了一套专门用于线程同步的mutex函数。
1.创建和销毁
(1)有两种方法创建互斥锁,静态方法和动态方法
POSIX定义了一个宏PTHREAD_MUTEX_INITIALIZER来静态初始化互斥锁,方法如下
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
在LinuxThreads实现中,pthread_mutex_t是一个结构,而
PTHREAD_MUTEX_INITIALIZER是一个结构常量。
2、锁操作
锁操作主要包括加锁pthread_mutex_lock(),解锁pthread_mutex_unlock(),
锁不可能被两个不同的线程同时得到,必须等待解锁。在同一进程中的线程,如果加锁后没有
解锁,则任何其他线程都无法在获得锁。
intpthread_mutex_lock(pthread_mutex_t *mutex)
int pthread_mutex_unlock(pthread_mutex_t*mutex)
二、条件变量
1、 条件变量是利用在线程间共享的全局变量进行同步的一种机制,主要包括动作:一个线程等待“条件变量的成立”而挂起;
一个线程使“条件成立”
(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合起来。
1. 创建和注销
条件变量和互斥锁一样,都有静态动态两种创建方式,静态方式使用PTHREAD_COND_INITIALIZER常量,如下:
pthread_cond_t cond=PTHREAD_COND_INITIALIZER
2. 等待和激发
intpthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)
无条件等待pthread_cond_wait()必须和一个互斥锁配合,以防止多个线程同时请求pthread_cond_wait()的竞争条件。mutex互斥锁必须是普通锁或者适应锁,在更新条件等待队列以前,mutex保持锁定状态,并在线程挂起进入等待前解锁。在条件满足从而离开pthread_cond_wait()之前,mutex将被重新加锁。
激发条件:pthread_cond_signal()激活一个等待该条件的线程,存在多个等待线程时按入队顺序激活其中一个;
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
intg_ flag=0;
staticpthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
staticpthread_cond_t cond=PTHREAD_COND_INITIALIZER;
void*thread1(void *argc)
{
printf("this is thread1\n");
pthread_mutex_lock(&mutex);
if(g_flag==2)
pthread_cond_signal(&cond);
g_flag=1;
pthread_mutex_unlock(&mutex);
pthread_join(*(pthread_t*)argc,NULL);
pthread_exit(0);
}
void*thread2(void *argc)
{
printf("this is thread2\n");
pthread_mutex_lock(&mutex);
if(g_flag==1)
pthread_cond_signal(&cond);
g_flag=2;
pthread_mutex_unlock(&mutex);
pthread_exit(0);
}
intmain()
{
printf("enter main\n");
pthread_t tid1,tid2;
int ret=0;
if((ret=pthread_create(&tid1,NULL,thread1,&tid2))!=0)
printf("create thread1error!\n");
if((ret=pthread_create(&tid2,NULL,thread2,NULL))!=0)
printf("create thread2error!\n");
pthread_cond_wait(&cond,&mutex);
printf("leave main\n");
return 0;
}