互斥锁
注意:如果man手册中查不到这系列函数,可以安装以下内容:
sudo apt-get install glibc-doc
sudo apt-get install manpages-posix-dev
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
功能:定义并初始化互斥锁
int pthread_mutex_init (pthread_mutex_t* mutex,const pthread_mutexattr_t* mutexattr);
功能:初始化一互斥锁,会被初始化为非锁定状态
int pthread_mutex_lock (pthread_mutex_t* mutex);
功能:加锁,当互斥锁已经是锁定状态时,调用者会阻塞,直到互斥被解开,当前线程才会加锁成功并返回。
int pthread_mutex_unlock (pthread_mutex_t* mutex);
功能:解锁,解锁后等待加锁的线程才能加锁成功。
int pthread_mutex_destroy (pthread_mutex_t* mutex);
功能:销毁锁
int pthread_mutex_trylock (pthread_mutex_t *__mutex)
功能:加测试锁,如果不加锁刚立即返回
int pthread_mutex_timedlock(pthread_mutex_t *restrict mutex,
const struct timespec *restrict abs_timeout);
功能:倒计时加锁,如果超时还不加上则立即返回。
struct timespec{
time_t tv_sec; /* Seconds. */
long int tv_nsec; /* Nanoseconds.*/ 1秒= 1000000000 纳秒
};
#include <stdio.h>
#include <pthread.h>
/*
执行流程:
1、互斥锁被初始化为非锁定状态
2、线程1调用pthread_mutex_lock函数,立即返回,互斥量呈锁定状态;
3、线程2调用pthread_mutex_lock函数,阻塞等待;
4、线程1调用pthread_mutex_unlock函数,互斥量呈非锁定状态;
5、线程2被唤醒,从pthread_mutex_lock函数中返回,互斥量呈锁定状态
*/
pthread_mutex_t mutex;
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int num = 0;
void* run(void* arg)
{
for(int i=0; i<1000000; i++)
{
pthread_mutex_lock(&mutex);
num++;
pthread_mutex_unlock(&mutex);
}
}
int main(int argc,const char* argv[])
{
pthread_mutex_init(&mutex,NULL);
pthread_t pid1,pid2;
pthread_create(&pid1,NULL,run,NULL);
pthread_create(&pid2,NULL,run,NULL);
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
pthread_mutex_destroy(&mutex);
printf("%d\n",num);
}