Linux应用编程—11.互斥锁
互斥锁是一种机制,用来保证共享资源在某一时刻只能被一个线程访问或修改,保证数据的一致性。互斥锁有两种状态,上锁和解锁。pthread_mutex_init()函数用来初始化互斥锁。
NAME
pthread_mutex_init, pthread_mutex_lock, pthread_mutex_trylock, pthread_mutex_unlock, pthread_mutex_destroy - operations on mutexes
SYNOPSIS
#include <pthread.h>
pthread_mutex_t fastmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t recmutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
pthread_mutex_t errchkmutex = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP;
int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
int pthread_mutex_destroy(pthread_mutex_t *mutex);
线程互斥锁有关的操作有初始化、上锁、尝试上锁、解锁、销毁互斥锁。使用相关函数时需要包含头文件pthread.h。int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);参数mutex是一个指针,指向互斥锁的地址;参数mutexattr可以写入NULL,代表使用默认属性。上锁操作使用函数原型为:int pthread_mutex_lock(pthread_mutex_t *mutex);解锁操作使用函数原型为: int pthread_mutex_unlock(pthread_mutex_t *mutex)。
11.1 互斥锁的使用
创建两个线程与一个全局变量i,因为线程之间资源共享,这个i对于这个两个线程都是可见的。初始化一个互斥锁,程序运行后,线程1让出CPU使用权,线程2上锁后,每隔1秒,将i变量执行++操作3次,并且打印输出如:0、1、2,然后解锁,延时1秒让出CPU使用权。等到线程1执行,同样上锁,每隔1秒,连续将i变量++操作3次,并且打印输出如:3、4、5,然后解锁延时1秒让出CPU使用权。这样程序的最终效果是:线程2中i变量每隔1秒打印一次,最后累加到2,然后线程1中i变量每隔1秒钟打印一次,最后累加到5,交替进行。
#include <pthread.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <semaphore.h>
#include <stdlib.h>
void *thread_fun1(void *arg);
void *thread_fun2(void *arg);
pthread_mutex_t mutex;;
int i = 0;
int main(void)
{
int ret = 0;
pthread_t thread1;
pthread_t thread2;
pthread_mutex_init(&mutex, NULL);
ret |= pthread_create(&thread1, NULL, thread_fun1, NULL);
if(0 != ret)
{
perror("thread_create.");
exit(1);
}
ret |= pthread_create(&thread2, NULL, thread_fun2, NULL);
if(0 != ret)
{
perror("thread_create.");
exit(1);
}
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
return 0;
}
void *thread_fun1(void *arg)
{
int index;
sleep(1);
while(1)
{
pthread_mutex_lock(&mutex);
for(index = 0; index < 3; index++)
{
printf("thread1, i = %d.\n", i++);
sleep(1);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
void *thread_fun2(void *arg)
{
int index;
while(1)
{
pthread_mutex_lock(&mutex);
for(index = 0; index < 3; index++)
{
printf("thread2, i = %d.\n", i++);
sleep(1);
}
pthread_mutex_unlock(&mutex);
sleep(1);
}
}
运行结果:
thread2, i = 0.
thread2, i = 1.
thread2, i = 2.
thread1, i = 3.
thread1, i = 4.
thread1, i = 5.
thread2, i = 6.
thread2, i = 7.
thread2, i = 8.
thread1, i = 9.
thread1, i = 10.
thread1, i = 11.
thread2, i = 12.
代码运行符合预期。