JackCin's blog JackCin's blog
首页
  • 页面

    • Html
    • CSS
  • 核心

    • JavaScript基础
    • JavaScript高级
  • 框架

    • Vue
  • jQuery
  • Node
  • Ajax
Linux
  • 操作系统
  • 数据结构与算法
  • 51单片机
  • CC2530
  • 网站
  • 分类
  • 标签
  • 归档
GitHub (opens new window)

JackCin

前端小菜鸡(✪ω✪)
首页
  • 页面

    • Html
    • CSS
  • 核心

    • JavaScript基础
    • JavaScript高级
  • 框架

    • Vue
  • jQuery
  • Node
  • Ajax
Linux
  • 操作系统
  • 数据结构与算法
  • 51单片机
  • CC2530
  • 网站
  • 分类
  • 标签
  • 归档
GitHub (opens new window)
  • Linux系统编程入门

  • Linux 多进程开发

  • Linux 多线程开发

    • 线程基础
    • 线程同步
      • 1、线程同步
        • 1.1 线程同步概念
        • 1.2 线程同步应用场景
      • 2、互斥锁
        • 2.1 互斥量概念
        • 2.2 互斥量函数
        • 2.3 互斥量实现线程同步
      • 3、死锁
        • 3.1 死锁概念
        • 3.2 死锁产生场景
        • 3.2.1 忘记释放锁
        • 3.2.2 重复加锁
        • 3.2.3 多线程多锁,抢占锁资源
        • 3.3 思考
      • 4、读写锁
        • 4.1 读写锁概念
        • 4.2 读写锁相关函数
      • 5、生产者消费者模型
        • 5.1 生产者消费者问题
        • 5.2 代码模拟
        • 5.3 互斥锁解决方法
      • 6、条件变量
        • 6.1 条件变量函数
        • 6.2 条件变量解决方法
      • 7、信号量
        • 7.1 信号量函数
        • 7.2 信号量使用伪代码
        • 7.3 信号量解决方法
        • 7.4 生产消费正确运行
  • Linux 网络编程

  • Linux
  • Linux 多线程开发
JackCin
2023-09-12
目录

线程同步

# 线程同步

# 1、线程同步

# 1.1 线程同步概念

  • 线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程修改的变量。
  • 临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作(必须一口气执行完不能执行一半被中断),也就是同时访问同一共享资源的其他线程不应中断该片段的执行。
  • 线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。

# 1.2 线程同步应用场景

/*
    使用多线程实现买票的案例。
    有3个窗口,一共是100张票。
*/

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 全局变量,所有的线程都共享这一份资源。
int tickets = 100;

void *sellticket(void *arg)
{
    // 卖票
    while (tickets > 0)
    {
        // 休眠1000微秒
        usleep(1000);
        printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
        tickets--;
    }
    return NULL;
}

int main()
{

    // 吵创建3个子进程
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, sellticket, NULL);
    pthread_create(&tid2, NULL, sellticket, NULL);
    pthread_create(&tid3, NULL, sellticket, NULL);

    // 回收子线程的资源,阻塞
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);

    // 设置线程分离。
    // pthread_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);

    pthread_exit(NULL); // 退出主线程

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

线程同步问题

  • 可以看到出现了3个线程卖同一张票或者,出现负票的情况
  • 卖同一张票: 几个线程都进入了循环,但是再执行到票数减少的语句前,线程切换执行,没有减少票数,导致说几个线程卖出了同一张票
  • 负票:几个线程在还有票数时进入了循环,但是线程切换执行,导致票数减少到负,但是已经进入循环了,所以还是会卖出票
  • 上面代码并不是说是因为加了休眠才会出现问题,只是加了休眠问题更明显,所以加了休眠,但是即使我们不加休眠就不会出问题,为了代码的健壮性,其实我们也应该考虑线程同步来解决上述问题

# 2、互斥锁

# 2.1 互斥量概念

  • 为避免线程更新共享变量时出现问题,可以使用**互斥量**(mutex 是 mutual exclusion 的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。
  • 互斥量有两种状态:已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。
  • 一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:
    • 针对共享资源锁定互斥量
    • 访问共享资源
    • 对互斥量解锁

互斥量图解

# 2.2 互斥量函数

//互斥量的类型 pthread_mutex_t
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
    - 初始化互斥量
    - 参数 :
        - mutex : 需要初始化的互斥量变量
        - attr : 互斥量相关的属性,NULL
    - restrict : C语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。如:
        pthread_mutex_t *restrict mutex = xxx;
        pthread_mutex_t * mutex1 = mutex; //这样是不可以的,因为mutex 已经被 restrict修饰

int pthread_mutex_destroy(pthread_mutex_t *mutex);
    - 释放互斥量的资源
int pthread_mutex_lock(pthread_mutex_t *mutex);
    - 加锁,阻塞的,如果有一个线程加锁了,那么其他的线程只能阻塞等待
int pthread_mutex_trylock(pthread_mutex_t *mutex);
    - 尝试加锁,如果加锁失败,不会阻塞,会接着执行之后的代码。
    - 如果加锁成功,会访问临界资源
int pthread_mutex_unlock(pthread_mutex_t *mutex);
    - 解锁
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
  • 补充:pthread_mutex_trylock_有朋山人的博客-CSDN博客 (opens new window)

# 2.3 互斥量实现线程同步

//mutex.c

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 全局变量,所有的线程都共享这一份资源。
int tickets = 1000;
// 创建一个互斥量(全局变量)
pthread_mutex_t mutex;

void *sellticket(void *arg)
{
    // 卖票
    while (1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        // 下面的操作就是我们的临界区
        if (tickets > 0)
        {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
            tickets--;
        }
        else
        {
            // 解锁(这里也必须解锁,不然如果直接就跳出来循环,会导致互斥量一直被占用,没有解锁)
            pthread_mutex_unlock(&mutex);
            break;
        }

        // 解锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main()
{
    // 初始化互斥量
    pthread_mutex_init(&mutex, NULL);

    // 创建3个子线程
    pthread_t tid1, tid2, tid3;
    pthread_create(&tid1, NULL, sellticket, NULL);
    pthread_create(&tid2, NULL, sellticket, NULL);
    pthread_create(&tid3, NULL, sellticket, NULL);

    // 回收子线程的资源,阻塞
    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);
    pthread_join(tid3, NULL);
    
    // 释放互斥量资源(join会阻塞,所以会等子进程都结束才释放)
    pthread_mutex_destroy(&mutex);
    
    pthread_exit(NULL); // 退出主线程
    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60

# 3、死锁

# 3.1 死锁概念

  • 有时,一个线程需要同时访问两个或更多不同的共享资源,而每个资源又都由不同的互斥量管理。当超过一个线程加锁同一组互斥量时,就有可能发生死锁。
  • 两个或两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁。
  • 死锁的几种场景:
    • 忘记释放锁
    • 重复加锁
    • 多线程多锁,抢占锁资源

# 3.2 死锁产生场景

# 3.2.1 忘记释放锁

//mutex.c

void *sellticket(void *arg)
{
    // 卖票
    while (1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        // 下面的操作就是我们的临界区
        if (tickets > 0)
        {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
            tickets--;
        }
        else
        {
            // 解锁(如果直接就跳出来循环,会导致互斥量一直被占用,没有解锁)
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁
        //pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  • 上面代码运行结果为: 正在卖第 1000 张门票 如果就被阻塞了,因为它忘记解锁,再次执行就导致了重复加锁,所以线程被阻塞

# 3.2.2 重复加锁

void *sellticket(void *arg)
{
    // 卖票
    while (1)
    {
        // 加锁
        pthread_mutex_lock(&mutex);
        pthread_mutex_lock(&mutex);
        // 下面的操作就是我们的临界区
        if (tickets > 0)
        {
            usleep(6000);
            printf("%ld 正在卖第 %d 张门票\n", pthread_self(), tickets);
            tickets--;
        }
        else
        {
            // 解锁(如果直接就跳出来循环,会导致互斥量一直被占用,没有解锁)
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁
        pthread_mutex_unlock(&mutex);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
  • 上面代码运行结果是直接被阻塞上面也没输出,因为重复加锁,导致了线程被阻塞

# 3.2.3 多线程多锁,抢占锁资源

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 创建2个互斥量
pthread_mutex_t mutex1, mutex2;

void *workA(void *arg)
{

    pthread_mutex_lock(&mutex1);
    sleep(1);
    pthread_mutex_lock(&mutex2);

    printf("workA....\n");
    // 注意解锁顺序,先锁后解,后锁先解
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    return NULL;
}

void *workB(void *arg)
{
    pthread_mutex_lock(&mutex2);
    sleep(1);
    pthread_mutex_lock(&mutex1);

    printf("workB....\n");

    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);

    return NULL;
}

int main()
{

    // 初始化互斥量
    pthread_mutex_init(&mutex1, NULL);
    pthread_mutex_init(&mutex2, NULL);

    // 创建2个子线程
    pthread_t tid1, tid2;
    pthread_create(&tid1, NULL, workA, NULL);
    pthread_create(&tid2, NULL, workB, NULL);

    // 回收子线程资源
    pthread_join(tid1, NULL); //会阻塞等待子进程结束
    pthread_join(tid2, NULL);

    // 释放互斥量资源
    pthread_mutex_destroy(&mutex1);
    pthread_mutex_destroy(&mutex2);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

抢占锁资源

  • 加sleep 是为了更好的表现出多线程多锁,抢占锁资源的效果,没有什么特殊含义
  • 可以看到后面的执行就是产生了死锁

# 3.3 思考

  • 为什么解锁顺序要先锁后解,后锁先解?

答:因为会给死锁创造条件,假设按照 加锁1-加锁2-解锁1-解锁2 的话,线程A在执行完解锁1时,可能线程B立刻执行加锁1,此时线程A持有互斥锁2,而线程B持有互斥锁1,这个时候就符合死锁的效果图?

抢占锁资源图

# 4、读写锁

# 4.1 读写锁概念

  • 当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。
  • 在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。 为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。
  • 读写锁的特点:
    • 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。
    • 如果有其它线程写数据,则其它线程都不允许读、写操作。
    • 写是独占的,写的优先级高。

# 4.2 读写锁相关函数

    // 读写锁的类型 pthread_rwlock_t
    int pthread_rwlock_init(pthread_rwlock_t *restrict rwlock, const pthread_rwlockattr_t *restrict attr);
    int pthread_rwlock_destroy(pthread_rwlock_t *rwlock);
    int pthread_rwlock_rdlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_tryrdlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_wrlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_trywrlock(pthread_rwlock_t *rwlock);
    int pthread_rwlock_unlock(pthread_rwlock_t *rwlock);

//函数作用和参数含义基本和互斥锁差不多
1
2
3
4
5
6
7
8
9
10

4.3 代码案例

//rwlock.c
/*
    案例:8个线程操作同一个全局变量。
    3个线程不定时写这个全局变量,5个线程不定时的读这个全局变量
*/

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>

// 创建一个共享数据
int num = 1;
pthread_rwlock_t rwlock;
// pthread_mutex_t mutex;

void *writeNum(void *arg)
{

    while (1)
    {
        pthread_rwlock_wrlock(&rwlock);
        // pthread_mutex_lock(&mutex);
        num++;
        printf("++write, tid : %ld, num : %d\n", pthread_self(), num);
        // pthread_mutex_unlock(&mutex);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }

    return NULL;
}

void *readNum(void *arg)
{

    while (1)
    {
        // pthread_mutex_lock(&mutex);
        pthread_rwlock_rdlock(&rwlock);
        printf("===read, tid : %ld, num : %d\n", pthread_self(), num);
        // pthread_mutex_unlock(&mutex);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }

    return NULL;
}

int main()
{
    // pthread_mutex_init(&mutex, NULL);
    pthread_rwlock_init(&rwlock, NULL);

    // 创建3个写线程,5个读线程
    pthread_t wtids[3], rtids[5];
    for (int i = 0; i < 3; i++)
    {
        pthread_create(&wtids[i], NULL, writeNum, NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_create(&rtids[i], NULL, readNum, NULL);
    }

    // 设置线程分离
    for (int i = 0; i < 3; i++)
    {
        pthread_detach(wtids[i]);
    }

    for (int i = 0; i < 5; i++)
    {
        // 这里最好还是用 join ,因为用detach的话是不阻塞的
        // 然后按下面终止主线程和释放锁的顺序,如果先终止,那释放就没执行
        // 如果先释放,那可能会因为子线程还没终止,却提前释放锁而出现问题(不是一定会出错)
        // 所以建议还是使用join比较好
        // 突然觉得这里也蛮奇怪的,因为子线程是死循环不会终止,如果用join那主线程也不会自动终止,而是在我们手动ctrl+c 终止子线程后才会终止
        pthread_detach(rtids[i]);
    }
    
    //看到后面知道了,老师解决上面问题的方法居然是用while不让主线程退出🤕🤕🤕,还是建议用join比较好
    while(1) {
        sleep(10);
    }
    
    

    pthread_exit(NULL);
	//先执行了 pthread_exit(NULL) 后面的语句相当于没执行,感觉老师这样写的顺序不对
    pthread_rwlock_destroy(&rwlock);
    // pthread_mutex_destroy(&mutex);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95

读写锁

  • 其实这里就是我们不是用的读写锁而是互斥锁,执行结果都是正确的,但是使用互斥锁的话,进行读取的线程并不是并发执行的,而是阻塞的,一个执行完解了锁,下一个才能执行。

# 5、生产者消费者模型

# 5.1 生产者消费者问题

  • 系统中有一组生产者进程和一组消费者进程。生产者进程每次生产一个产品放入缓冲区,消费者进程每次从缓冲区中取出一个进程并使用,那么他们之间具有这样一层关系:
  • 生产者、消费者共享一个初始为空、大小为n的缓冲区。
    • 只有缓冲区没满时,生产者才能把产品放入缓冲区。否则必须等待 (缓冲区没满->生产者生产)
    • 只有缓冲区不空时,消费者才能从中取出产品,否则必须等待 (缓冲区不空->消费者消费)
    • 缓冲区是临界资源,各进程访问时要求互斥 (互斥访问)

img

# 5.2 代码模拟

//prodcust.c
/*
    生产者消费者模型(粗略的版本)
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

struct Node
{
    int num;
    struct Node *next;
};

// 头结点
struct Node *head = NULL;
void *producer(void *arg)
{
    // 不断的创建新的节点,添加到链表中
    while (1)
    {
        //这里用的是头插法
        struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num = rand() % 1000;
        printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
        usleep(100);
    }

    return NULL;
}

void *customer(void *arg)
{

    while (1)
    {
        // 保存头结点的指针
        struct Node *tmp = head;
        head = head->next;
        printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
        free(tmp);
        usleep(100);
    }
    return NULL;
}

int main()
{

    // 创建5个生产者线程,和5个消费者线程
    pthread_t ptids[5], ctids[5];

    for (int i = 0; i < 5; i++)
    {
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while (1)
    {
        sleep(10);
    }

    pthread_exit(NULL);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

生产消费问题

  • 这里编译生成 prodcust 可执行文件时记得加 -g 生成调试信息,不然我们没办法查看 core

  • 查看 core:

    生产消费问题core

  • SIGSEGV :可以看出进行了无效内存访问(段错误)

  • 原因就是当我们链表被删除完后,就没有了head结点,所以生成线程执行到 head = head->next语句就出现了段错误

  • 下面给出3种解决方法,注意下面3种方法都是需要用到互斥量或者与互斥量搭配使用

# 5.3 互斥锁解决方法

/*
    生产者消费者模型(粗略的版本)
*/
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

// 创建一个互斥量
pthread_mutex_t mutex;

struct Node{
    int num;
    struct Node *next;
};

// 头结点
struct Node * head = NULL;

void * producer(void * arg) {

    // 不断的创建新的节点,添加到链表中
    while(1) {
        pthread_mutex_lock(&mutex);
        //这里用的是头插法
        struct Node * newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num = rand() % 1000;
        printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }

    return NULL;
}

void * customer(void * arg) {

    while(1) {
        pthread_mutex_lock(&mutex);
        // 保存头结点的指针
        struct Node * tmp = head;

        // 判断是否有数据
       // 这样的写法的问题是,如果head == NULL,那么就会一直循环判断而不做其他事情,这样很浪费资源
        if(head != NULL) {
            // 有数据
            head = head->next;
            printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
            free(tmp);
            pthread_mutex_unlock(&mutex);
            usleep(100);
        } else {
            // 没有数据
            pthread_mutex_unlock(&mutex);
        }
    }
    return  NULL;
}

int main() {

    pthread_mutex_init(&mutex, NULL);

    // 创建5个生产者线程,和5个消费者线程
    pthread_t ptids[5], ctids[5];

    for(int i = 0; i < 5; i++) {
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }

    for(int i = 0; i < 5; i++) {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while(1) {
        sleep(10);
    }

    pthread_mutex_destroy(&mutex);

    pthread_exit(NULL);

    return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
  • 只用互斥锁解决的写法的问题是:
    • 当缓冲区为空,不用条件变量时,消费者处于无意义的循环,此时只执行加锁和解锁,直到时间片完才发生线程切换,浪费cpu资源。而加入条件变量,一旦发现缓存区是空的,会立刻从运行态进入阻塞态,此时一定会发生线程切换,把cpu资源让出。互斥锁和条件变量都可以实现线程同步,但使用条件变量效率更高。

# 6、条件变量

# 6.1 条件变量函数

  //条件变量的类型 pthread_cond_t
    int pthread_cond_init(pthread_cond_t *restrict cond, const pthread_condattr_t *restrict attr);
    int pthread_cond_destroy(pthread_cond_t *cond);
    int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex);
        - 等待,调用了该函数,线程会阻塞。
        - 当这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞的,继续向下执行,会重新加锁。
    int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
        - 等待多长时间,调用了这个函数,线程会阻塞,直到指定的时间结束。
    int pthread_cond_signal(pthread_cond_t *cond);
        - 唤醒一个或者多个等待的线程
    int pthread_cond_broadcast(pthread_cond_t *cond);
        - 唤醒所有的等待的线程
1
2
3
4
5
6
7
8
9
10
11
12

# 6.2 条件变量解决方法

//cond.c

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

// 创建一个互斥量
pthread_mutex_t mutex;
// 创建条件变量
pthread_cond_t cond;

struct Node
{
    int num;
    struct Node *next;
};

// 头结点
struct Node *head = NULL;

void *producer(void *arg)
{

    // 不断的创建新的节点,添加到链表中
    while (1)
    {
        pthread_mutex_lock(&mutex);
        struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num = rand() % 1000;
        printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());

        // 只要生产了一个,就通知消费者消费
        //注意:signal是唤醒一个或者多个睡眠的线程,如果数据足够多,线程没有休眠,即使收到了信号也不会做任何的处理。
        pthread_cond_signal(&cond);

        pthread_mutex_unlock(&mutex);
        usleep(100);
    }

    return NULL;
}

void *customer(void *arg)
{

    while (1)
    {
        pthread_mutex_lock(&mutex);
        // 保存头结点的指针
        struct Node *tmp = head;
        // 判断是否有数据
        if (head != NULL)
        {
            // 有数据
            head = head->next;
            printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
            free(tmp);
            pthread_mutex_unlock(&mutex);
            usleep(100);
        }
        else
        {
            // 没有数据,需要等待
            // 当这个函数调用阻塞的时候,会对互斥锁进行解锁,当不阻塞的时候,继续向下执行,会重新加锁。
            pthread_cond_wait(&cond, &mutex);
            pthread_mutex_unlock(&mutex);
        }
    }
    return NULL;
}

int main()
{
	//初始化互斥锁和条件变量
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    // 创建5个生产者线程,和5个消费者线程
    pthread_t ptids[5], ctids[5];

    for (int i = 0; i < 5; i++)
    {
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while (1)
    {
        sleep(10);
    }

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    pthread_exit(NULL);

    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
  • 使用条件变量就解决了我们只用互斥锁,导致的没有数据时,消费者一直重复循环判断,浪费资源的问题
  • 注意:当线程执行到 pthread_cond_wait(&cond, &mutex)时,会对互斥锁进行解锁,这是生产者就可以继续生产,直到线程执行到 pthread_cond_signal(&cond) ,并且再执行 pthread_mutex_unlock(&mutex)解锁操作后,那么wait就取消阻塞的同时重新加锁,继续向下执行。

# 7、信号量

# 7.1 信号量函数

 信号量的类型 sem_t
    int sem_init(sem_t *sem, int pshared, unsigned int value);
        - 初始化信号量
        - 参数:
            - sem : 信号量变量的地址
            - pshared : 0 用在线程间 ,非0 用在进程间
            - value : 信号量中的值

    int sem_destroy(sem_t *sem);
        - 释放资源

    int sem_wait(sem_t *sem);
        - 对信号量加锁,调用一次对信号量的值-1,如果值为0,就阻塞

    int sem_trywait(sem_t *sem);

    int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
		- 如果是0的话阻塞多长时间
    int sem_post(sem_t *sem);
        - 对信号量解锁,调用一次对信号量的值+1

    int sem_getvalue(sem_t *sem, int *sval);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 7.2 信号量使用伪代码

    sem_t psem; //生产者信号量
    sem_t csem;  //消费者信号量
    init(psem, 0, 8);  //给一个值就行
    init(csem, 0, 0);

    producer() {
        sem_wait(&psem);  //开始生产 ,一个生产者正在工作,所以生产信号 -1
        
        // 执行代码(生产)
        
        sem_post(&csem)  //生产结束 ,有一个产品可以消费 ,所以消费信号 +1
    }

    customer() {
        sem_wait(&csem);  //开始消费 ,一个消费者正在消费,所以消费信号 -1
        
        //执行代码(消费)
        
        sem_post(&psem)  //消费结束 ,空出空位给生产者进行生产,生产信号 +1
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20

# 7.3 信号量解决方法

//semaphore.c

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
#include <semaphore.h>

// 创建一个互斥量
pthread_mutex_t mutex;
// 创建两个信号量
sem_t psem;
sem_t csem;

struct Node
{
    int num;
    struct Node *next;
};

// 头结点
struct Node *head = NULL;

void *producer(void *arg)
{

    // 不断的创建新的节点,添加到链表中
    while (1)
    {
        sem_wait(&psem);
        pthread_mutex_lock(&mutex);
        struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
        newNode->next = head;
        head = newNode;
        newNode->num = rand() % 1000;
        printf("add node, num : %d, tid : %ld\n", newNode->num, pthread_self());
        pthread_mutex_unlock(&mutex);
        sem_post(&csem);
    }

    return NULL;
}

void *customer(void *arg)
{

    while (1)
    {
        sem_wait(&csem);
        pthread_mutex_lock(&mutex);
        // 保存头结点的指针
        struct Node *tmp = head;
        head = head->next;
        printf("del node, num : %d, tid : %ld\n", tmp->num, pthread_self());
        free(tmp);
        pthread_mutex_unlock(&mutex);
        sem_post(&psem);
    }
    return NULL;
}

int main()
{

    pthread_mutex_init(&mutex, NULL);
    sem_init(&psem, 0, 8);
    sem_init(&csem, 0, 0);

    // 创建5个生产者线程,和5个消费者线程
    pthread_t ptids[5], ctids[5];

    for (int i = 0; i < 5; i++)
    {
        pthread_create(&ptids[i], NULL, producer, NULL);
        pthread_create(&ctids[i], NULL, customer, NULL);
    }

    for (int i = 0; i < 5; i++)
    {
        pthread_detach(ptids[i]);
        pthread_detach(ctids[i]);
    }

    while (1)
    {
        sleep(10);
    }

    pthread_mutex_destroy(&mutex);

    pthread_exit(NULL);

    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
  • 信号量主要是阻塞线程但是不能保证数据的安全,为了保证数据安全信号量要和互斥锁一起使用(好比上面如果不用互斥锁,就可能会出现链表结点创建一半其他线程又抢占时间片,进行创建,这样就会导致链表出错)

# 7.4 生产消费正确运行

解决生产消费问题

  • 因为我们是头插法,删除也是从头节点开始删,所以会是上图的样子
  • 个人感觉:(使用信号量的话,数据量就有了上限,使用条件变量的话,有些场景还是需要自己代码判断)
编辑 (opens new window)
上次更新: 2023/09/13, 12:29:52
线程基础
网络基础

← 线程基础 网络基础→

最近更新
01
51单片机及补充知识
09-13
02
独立按键
09-13
03
LCD1602液晶显示器
09-13
更多文章>
Theme by Vdoing | Copyright © 2019-2023 Evan Xu | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式