线程同步(锁/信号量)

声明: 本篇博客的学习途径主要为以下网站和课堂讲解,发博客目的仅为学习使用,在该博客的基础上做了一定程序的简略和修改。
参考博客 :
原文链接:
https://blog.csdn.net/isunbin/article/details/83415873
https://www.zhihu.com/question/66733477?sort=created

线程同步

多线程之间可能需要互斥的访问一些全局变量,这就需要互斥的来访问,这些需要共享访问的字段被称作是临界资源,访问临界资源的程序段称作是临界区。
实现线程间的互斥与同步机制的是锁机制
在这里插入图片描述

互斥锁

分析:

pthread_mutex_t mutex
  • pthread_mutex_t 类型,其本质是一个结构体,为简化理解,应用时可忽略其实现细节,简单当成整数看待。
  • pthread_mutex_t mutex:变量mutex只有两种取值0、1;

【实例】demo1-1

#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
 
void *tfn(void *arg)
{
    srand(time(NULL));
 
    while(1) {
        printf("hello ");
        sleep(rand() % 3); //模拟长时间操作共享资源,导致cpu易主,产生与时间有关的错误
        printf("word\n");
        sleep(rand() % 3);
    }
    return NULL;
}
 
int main()
{
    pthread_t tid;
    srand(time(NULL));
 
    pthread_create(&tid, NULL, tfn, NULL);
    while(1) {
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        sleep(rand() % 3);
    }
    return 0;
}
[root@localhost src]# gcc -g test.c -pthread
[root@localhost src]# ./a.out
HELLO hello WORLD
word
hello word
hello HELLO WORLD
word
hello word
HELLO hello word
hello word 
WORlD

【实例】demo1-2 对函数线程进行加锁

#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
 
pthread_mutex_t mutex;
  
void *tfn(void *arg)
{
    srand(time(NULL));
 
    while(1) {
    	pthread_mutex_lock(&mutex);
        printf("hello ");
        sleep(rand() % 3);  //模拟长时间共享资源,导致cpu易主。产生于时间有关的错误 
        printf("word\n");
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 3);
    }
    return NULL;
}
 
int main()
{
    pthread_t tid;
    srand(time(NULL));
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid, NULL, tfn, NULL);  //mutex == 1
    while(1) {
    	pthread_mutex_lock(&mutex);
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");
        pthread_mutex_unlock(&mutex);
        sleep(rand() % 3);
    }
    
    pthread_mutex_destroy(&mutex);
    return 0;
}
[root@localhost src]# gcc -g test2.c -pthread
[root@localhost src]# ./a.out
HELLO WORLD
hello word
HELLO WORLD
hello word
HELLO WORLD
HELLO WORLD
hello word
HELLO WORLD
hello word

【实例】demo1-3 对函数线程和主线程都进行加锁

#include<pthread.h>
#include<stdlib.h>
#include<unistd.h>
 
pthread_mutex_t mutex;
  
void *tfn(void *arg)
{
    srand(time(NULL));
 
    while(1) {
    	pthread_mutex_lock(&mutex);
        printf("hello ");
        sleep(rand() % 3);  //模拟长时间共享资源,导致cpu易 主。产生于时间有关的错误 
        printf("word\n");
        sleep(rand() % 3);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
 
int main()
{
    pthread_t tid;
    srand(time(NULL));
    pthread_mutex_init(&mutex, NULL);
    pthread_create(&tid, NULL, tfn, NULL);  //mutex == 1
    while(1) {
    	pthread_mutex_lock(&mutex);
        printf("HELLO ");
        sleep(rand() % 3);
        printf("WORLD\n");       
        sleep(rand() % 3);
        pthread_mutex_unlock(&mutex);
    }
    
    pthread_mutex_destroy(&mutex);
    return 0;
}
[root@localhost src]# gcc -g test2.c -pthread
[root@localhost src]# ./a.out
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD
HELLO WORLD

【提问】为什么demo1-3的输出会一直是HELLO WORLD?另一个线程为啥不执行呢?
主进程的线程优先唤醒,并且进入了死循环,所以函数线程进不来。


pthread_mutex_init() 互斥锁初始化

功能:初始化一个互斥锁(互斥量);\rightarrow 初值可看做1

#include<pthread.h>
pthread_mutex_init(pthread_mutex_t *restrict mutex, 
                   const pthread_mutexattr_t *restrict attr);   

【参数】

  • mutex:锁对象,调用时应传&mutex
    • restrict关键字:只用于限制指针,告诉编译器,所有修改该指针指向内存中内容的操作只能通过本指针完成。不能通过除本指针以外的其他变量或指针修改。
  • attr:互斥属性。是一个传入参数,通常传NULL,选用默认属性(线程间共享).
    • 静态初始化:如果互斥锁mutex是静态分配的(定义在全局,或加了static关键字修饰),可以直接使用宏进行初始化。pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    • 动态初始化:局部变量应采用动态初始化。pthread_mutex_init(&mutex, NULL);

【返回值】

  • 若成功,返回0
  • 否则,返回错误编号

pthread_mutex_lock() 互斥锁直接上锁

功能:加锁。可理解为将mutex–(或-1)

#include<pthread.h>
pthread_mutex_lock(pthread_mutex_t *mutex);                                    

【返回值】

  • 若成功,返回0
  • 否则,返回错误编号

【情况分析】

  • 如果没有被上锁,当前线程会将这把锁锁上
  • 被锁上了:当前线程阻塞,锁被打开之后,线程解除阻塞。

pthread_mutex_trylock()尝试上锁

功能:尝试加锁, 失败返回, 不阻塞

#include<pthread.h>
pthread_mutex_trylock(pthread_mutex_t *mutex);

【返回值】

  • 若成功,返回0
  • 否则,返回错误编号

pthread_mutex_unlock() 互斥锁解锁

功能:解锁。可理解为将mtex++(或+1)

#include<pthread.h>
pthread_mutex_unlock(pthread_mutex_t *mutex);

【返回值】

  • 若成功,返回0
  • 否则,返回错误编号

【注意】

  • 同时将阻塞在该锁上的所有线程 全部唤醒

pthread_mutex_destroy()销毁互斥锁

功能:销毁一个互斥锁

#include<pthread.h>
pthread_mutex_destroy(pthread_mutex_t *mutex); 

【返回值】:

  • 若成功,返回0,
  • 否则,返回错误编号

加锁和解锁总结对比

【加锁和解锁对比】lock与unlock:

  • lock尝试加锁,如果加锁不成功,线程阻塞,阻塞到持有该互斥量的其他线程解锁为止。
  • unlock主动解锁,同时将阻塞到该锁上所有线程全部唤醒,至于哪个线程先被唤醒取决于优先级,调度。默认:先阻塞、先唤醒。

【两种加锁方式对比】lock与trylock:

  • lock加锁失败会阻塞,等待锁释放。
  • trylock加锁失败直接返回错误号(如EBUSY),不阻塞。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值