【Linux系统编程】Linux多线程开发-线程同步

线程同步

  • 线程的主要优势在于,能够通过全局变量来共享信息。不过这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量,或者某线程不会读取正在由其他线程修改的变量。
  • 临界区:指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作(不可被分割),也就是同时访问同一共享资源的其他线程不应中断该片段的执行。
  • 线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。
互斥量
  • 为避免线程更新共享变量时出现问题,可以使用互斥量(mutex: mutual exclusion)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。
  • 互斥量有两种状态∶已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。
  • 一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:
    • 针对共享资源锁定互斥量
    • 访问共享资源
    • 对互斥量解锁

如果多个线程试图执行这一块代码(一个临界区),事实上只有一个线程能够持有该互斥量(其他线程将遭到阻塞),即同时只有一个线程能够进入这段代码区域。

在这里插入图片描述

互斥量的类型:pthread_mutex_t
   
int pthread _mutex_init(pthread _mutex_t *restrict mutex,const pthread_mutexattr_t *restrict attr);
    功能:初始化互斥量
    参数:
        - mutex: 需要初始化的互斥量变量
            restrict: C语言的修饰符,被修饰的指针所指向的变量不能由另外的一个指针进行操作。
        - attr: 互斥量相关的属性,NULL

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);
    功能:解锁

示例:3个线程同时卖1000张票

#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(3000); // 睡眠3000微秒
            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);
    // 释放互斥量资源
    pthread_mutex_destroy(&mutex);
    pthread_exit(NULL); // 退出主线程
    return 0;
}
死锁
  • 有时一个线程需要同时访问两个或更多不同的共享资源.而每个资源又都由不同的互斥量管理。当超过一个线程加锁同一组互斥量时,就有可能发生死锁。
  • 两个或两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁。
  • 死锁的几种场景:
    • 忘记释放锁
    • 重复加锁
    • 多线程多锁,抢占锁资源

在这里插入图片描述

示例:多线程多锁,抢占锁资源

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 全局变量,所有线程共享同一资源
int tickets = 1000;
// 创建一个互斥量
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;
void* workA(void* arg)
{
    while(1)
    {
        // 加锁
        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)
{
    while(1)
    {
        // 加锁
        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);
    // 创建3个子线程
    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);
    pthread_exit(NULL); // 退出主线程
    return 0;
}
读写锁
  • 当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源。而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性.所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。
  • 在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。
  • 为了满足当前能够允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。
  • 读写锁的特点:
    • 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作。
    • 如果有其它线程写数据,则其它线程都不允许读、写操作。
    • 写是独占的,写的优先级高。
读写锁的类型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)

示例:

// 案例:8个线程操作同一个全局变量
// 有3个线程不定时写全局变量,5个线程不定时读这个全局变量
#define _XOPEN_SOURCE 500
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
// 创建一个共享数据
int num = 1;
pthread_rwlock_t rwlock;
void* writeNum(void* arg)
{
    while(1){
        pthread_rwlock_wrlock(&rwlock);
        ++num;
        printf("++write, tid: %ld, num: %d\n", pthread_self(), num);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}
void* readNum(void* arg)
{
    while(1){
        pthread_rwlock_rdlock(&rwlock);
        printf("===write, tid: %ld, num: %d\n", pthread_self(), num);
        pthread_rwlock_unlock(&rwlock);
        usleep(100);
    }
    return NULL;
}
int main()
{
    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(&wtids[i], NULL, readNum, NULL);
    // 设置线程分离
    for(int i = 0; i < 3; i++) pthread_detach(wtids[i]);
    for(int i = 0; i < 5; i++) pthread_detach(rtids[i]);
    pthread_exit(NULL);
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

注意:使用读写锁未定义的问题

最后查文档解决方是:在程序开头加入:#define _XOPEN_SOURCE 500*

生产者消费者模型

在这里插入图片描述

条件变量
条件变量的类型: pthrged_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);
    功能:阻塞函数:(线程)等待唤醒。
        当函数调用阻塞的时候,输入的mutex会被设置为解锁状态
        等待被唤醒后,将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);
    功能:唤醒所有等待的线程。

示例:生产者消费者模型 在消费者和生产者之间设置互斥量,对临界区只能同时有一个线程在运行;设置条件变量,当容器中不再有物品时,消费者会堵塞;生产者在生产完一个物品后,会唤醒消费者继续进行消费。(基于条件变量)

#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());
        // 只要生产了一个就通知消费者消费
        pthread_cond_signal(&cond);
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    return NULL;
}
void* customer(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex);
        // 判断是否有数据
        if(head != NULL) 
        {
            // 有数据
            // 保存头结点的指针
            struct Node *tmp = head;
            head = head->next;
            printf("del node, num: %d, tid: %ld\n", tmp->num, pthread_self());
            free(tmp);
        }
        else{
            // 没有数据,需要等待
            pthread_cond_wait(&cond, &mutex);
            printf("有数据了,开始冲\n");
        }
        pthread_mutex_unlock(&mutex);
        usleep(100);
    }
    return NULL;
}
int main()
{
    // 初始化mutex
    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_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    pthread_exit(NULL);
    return 0;
}
信号量

目的:阻塞线程,但不能保证多线程数据安全问题(需要用mutex)

信号量的类型: 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次,对信号量的值value 减1,如果值为0就堵塞。
int sem_trywait (sem_t *sem);
int sem_timedwait (sem_t *sem,const struct timespec *abs_timeout);

int sem_post (sem_t *sem);
    功能:对信号量解锁。每调用1次,对信号量的值value 加1int sem_getvalue (sem_t *sem, int *sval);

示例:生产者消费者模型 在消费者和生产者之间设置互斥量,对临界区只能同时有一个线程在运行;设置条件变量,当容器中不再有物品时,消费者会堵塞;生产者在生产完一个物品后,会唤醒消费者继续进行消费。(基于信号量)

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

// 创建一个互斥量
pthread_mutex_t mutex;
// 创建信号量
sem_t psem, 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());
        sem_post(&csem);
        pthread_mutex_unlock(&mutex);
    }
    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);
        sem_post(&psem);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main()
{
    // 初始化mutex
    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);
    sem_destroy(&csem);
    sem_destroy(&psem);
    pthread_exit(NULL);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Beyon.sir

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值