1.上锁 pthread_mutex_lock函数实现对互斥锁上锁,若互斥锁已经上锁,则调用者一直阻塞,直到互斥锁解锁后再上锁。
#include <pthread.h>
//上锁
int pthread_mutex_lock(pthread_mutex_t *mutex);
//尝试获得锁
int pthread_mutex_trylock(pthread_mutex_t *mutex);
参数: - mutex:互斥锁地址。
返回值: - 成功:0, 失败:非 0 错误码
2.解锁 pthread_mutex_unlock函数实现对指定的互斥锁解锁。
#include <pthread.h>
//解锁
int pthread_mutex_unlock(pthread_mutex_t * mutex);
参数: - mutex:互斥锁地址。
返回值: - 成功:0,失败:非 0 错误码
3.销毁锁 pthread_mutex_destroy函数实现销毁指定的一个互斥锁。互斥锁在使用完毕后,必须要对互斥锁进行销毁,以释放资源。
#include <pthread.h>
//销毁
int pthread_mutex_destroy(pthread_mutex_t *mutex);
参数: - mutex:互斥锁地址。
返回值: - 成功:0,失败:非 0 错误码
实例:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
pthread_mutex_t mutex; //互斥锁
// 打印机
void printer(char *str)
{
pthread_mutex_lock(&mutex); //上锁
while(*str!='\0')
{
putchar(*str);
fflush(stdout);
str++;
sleep(1);
}
printf("\n");
pthread_mutex_unlock(&mutex); //解锁
}
// 线程一
void *thread_fun_1(void *arg)
{
char *str = "hello,linux";
printer(str); //打印
}
// 线程二
void *thread_fun_2(void *arg)
{
char *str = "hello,world";
printer(str); //打印
}
int main(void)
{
pthread_t tid1, tid2;
pthread_mutex_init(&mutex, NULL); //初始化互斥锁
// 创建 2 个线程
pthread_create(&tid1, NULL, thread_fun_1, NULL);
pthread_create(&tid2, NULL, thread_fun_2, NULL);
// 等待线程结束,回收其资源
pthread_join(tid1, NULL);
pthread_join(tid2, NULL);
pthread_mutex_destroy(&mutex); //销毁互斥锁
return 0;
}
执行结果:
[root@iz2zefozq9h39txdb8s7npz shelldemo]# ./a.out
hello,world
hello,linux