线程同步(互斥量、死锁、读写锁、生产者与消费者模型实现)

线程同步

  在多线程进行

  线程的主要优势在于,能够通过全局变量来共享信息。不过,这种便捷的共享是有代价的:必须确保多个线程不会同时修改同一变量,或者某一线程不会读取正在由其他线程修改的变量。

  临界区是指访问某一共享资源的代码片段,并且这段代码的执行应为原子操作,也就是同时访问同一共享资源的其他线程不应终端该片段的执行。

  线程同步:即当有一个线程在对内存进行操作时,其他线程都不可以对这个内存地址进行操作,直到该线程完成操作,其他线程才能对该内存地址进行操作,而其他线程则处于等待状态。


互斥量 mutex

  为避免线程更新共享变量时出现问题,可以使用互斥量(mutex 是 mutual exclusion的缩写)来确保同时仅有一个线程可以访问某项共享资源。可以使用互斥量来保证对任意共享资源的原子访问。

  互斥量有两种状态已锁定(locked)和未锁定(unlocked)。任何时候,至多只有一个线程可以锁定该互斥量。试图对已经锁定的某一互斥量再次加锁,将可能阻塞线程或者报错失败,具体取决于加锁时使用的方法。

  一旦线程锁定互斥量,随即成为该互斥量的所有者,只有所有者才能给互斥量解锁。一般情况下,对每一共享资源(可能由多个相关变量组成)会使用不同的互斥量,每一线程在访问同一资源时将采用如下协议:

  • 针对共享资源锁定互斥量
  • 访问共享资源
  • 对互斥量解锁

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


mutex 相关系统调用

  1. 函数原型
	int pthread_mutex_init(pthread_mutex_t* restrict  mutex, const pthread_mutexattr_t* restrict attr);
    - 功能:初始化互斥量
    - 参数:
        - mutex :需要初始化的互斥量变量
        - attr  :互斥量相关的属性,NULL
    
    int pthread_mutex_destory(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);
    - 功能:解锁

restrict : C 语言的修饰符,被修饰的指针,不能由另外的一个指针进行操作。


示例1: 多线程买票实现,互斥锁实现

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

int tickets = 100;      // 全局变量,线程共享
pthread_mutex_t mutex;

void* sellticket(void* arg){
    // 卖票
    // int tickets = 100;      // 局部变量,每个线程会卖100张
    while (1){
         // 加锁
        pthread_mutex_lock(&mutex);
        if (tickets > 0){
            usleep(1000);
            printf("thread id : %ld, sell %dth ticket\n", pthread_self(), tickets);
            tickets--;
        }
        else{
            // 解锁
            pthread_mutex_unlock(&mutex);
            break;
        }
        // 解锁
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}


// 使用多线程实现买票的案例,3个窗口,一共100张票
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_detach(tid1);
    // pthread_detach(tid2);
    // pthread_detach(tid3);

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

    // 释放互斥量
    pthread_mutex_destroy(&mutex);

    return 0;
}

使用互斥量 mutex 对资源进行加锁,使得多个线程同时访问一个共享资源
mutex


死锁

  有时,一个线程需要同时访问两个或更多不同的共享资源,而每个资源又都由不同的互斥量管理。当超过一个线程加锁同一组互斥量时,就有可能发生死锁

  两个或两个以上的进程在执行过程中,因争夺共享资源而造成的一种互相等待的现象,若无外力作用,它们都将无法推进下去。此时称系统处于死锁状态或系统产生了死锁。死锁的几种场景:

  • 忘记释放锁
  • 重复加锁
  • 多线程多锁,抢占锁资源

示例2:死锁(多线程多锁)

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

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);
    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);

    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_exit(NULL);

    pthread_mutex_destroy(&mutex1);
    pthread_mutex_destroy(&mutex2);
    return 0;
}

线程1 在得到 mutex1 后,睡眠1s, 线程2得到 mutex2 ,此时线程2还需要 mutex1, 而 mutex1 还未被释放,线程1 也在请求 mutex2 ,资源被相互抢占,未被释放,所以造成死锁。
lock


读写锁

  当有一个线程已经持有互斥锁时,互斥锁将所有试图进入临界区的线程都阻塞住。但是考虑一种情形,当前持有互斥锁的线程只是要读访问共享资源,而同时有其它几个线程也想读取这个共享资源,但是由于互斥锁的排它性,所有其它线程都无法获取锁,也就无法读访问共享资源了,但是实际上多个线程同时读访问共享资源并不会导致问题。

  在对数据的读写操作中,更多的是读操作,写操作较少,例如对数据库数据的读写应用。为了满足当前能够 允许多个读出,但只允许一个写入的需求,线程提供了读写锁来实现。

读写锁的特点:

  • 如果有其它线程读数据,则允许其它线程执行读操作,但不允许写操作
  • 如果有其它线程写数据,则其它线程都不允许读、写操作
  • 写是独占的,写的优先级高

系统调用

// 读写锁的类型 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);

示例3:读写锁,对全局变量进行读写,多个线程可以同时读,但只允许一个线程进行写操作



/*
    8个线程操作同一个全局变量
    其中,3个线程不定时写,5个线程不定时读全局变量

*/

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

// 全局变量
int num = 0;
// pthread_mutex_t mutex;   // 互斥锁
pthread_rwlock_t rwlock;    // 读写锁

void* writeNum(void* arg){
    while (1)
    {
        // pthread_mutex_lock(&mutex);
        pthread_rwlock_wrlock(&rwlock);
        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++){
        pthread_detach(rtids[i]);
    }

    pthread_exit(NULL);

    // 释放锁
    // pthread_mutex_destroy(&mutex);
    pthread_rwlock_destroy(&rwlock);
    return 0;
}

条件变量实现生产者与消费者模型

  生产者与消费者模型中三个对象:生产者、消费者、容器。在多线程中,要保证线程同步,生产者与消费者如何配合使用容器:

  1. 在生产者生产后,容器已满,生产者阻塞,需要通知消费者消费,在消费后通知生产者
  2. 在消费者消费后,容器为空,消费者阻塞,需要通知生产者生产,在生产后通知消费者

在多个生产者与多个消费者的模型下,还需考虑多线程同步过程中,资源互斥的问题:

  1. 当多个消费者同时从容器中消费时,需要使用互斥量进行互斥访问

条件变量:使用条件变量,可以使得线程阻塞,等待某个条件满足,解除线程阻塞,所以可以解决无需 while(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);
// 等待多长时间,调用该函数,线程阻塞time 时间
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict abstime);
// 唤醒1 个/ 多个线程
int pthread_cond_signal(pthread_cond_t *cond);		
// 广播,唤醒所有线程
int pthread_cond_broadcast(pthread_cond_t *cond);

示例4: 使用信号量与互斥量实现生产者与消费者模型

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

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

// 头结点
Node* head = NULL;

// 问题1: 生产者数据同步问题      消费者数据同步问题
// 改进1: 多个生产者,需要进行互斥访问(互斥量解决)
pthread_mutex_t mutex;

// 问题2: 通过while(1) ,不停的判断,浪费性能
// 改进3: 当生产者生产数据后,发送通知给消费者(条件变量)
// 创建条件变量
pthread_cond_t cond;

void* producer(void* arg){
    // 生产者创建节点,添加到链表中
    while (1){
        // 共享数据加锁
        pthread_mutex_lock(&mutex);

        // 头插法
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->next = head;
        newNode->num = rand() % 1000;
        head = newNode;
        printf("Add node, num: %d, tid: %ld\n", newNode->num, pthread_self());

        // 生产1个,通知消费者消费
        pthread_cond_signal(&cond);     // 通知线程,解除阻塞

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

// 
void* customer(void* arg){
    // 问题2: 通过while(1) ,不停的判断,浪费性能
    // 改进3: 当生产者生产数据后,发送通知给消费者
    while (1){      
        // 共享数据加锁
        pthread_mutex_lock(&mutex);

        Node* cur = head;

        // 改进2 : 判断是否有数据,有数据再进行消费
        if (head != NULL){  // 有数据
            head = head->next;
            printf("delete node num: %d, tid: %ld\n", cur->num, pthread_self());
            free(cur);

            // 解锁
            pthread_mutex_unlock(&mutex);
            usleep(100);
        }
        else{               // 没有数据

            // 在 if 前得到 mutex ,线程阻塞,在 wait 中释放锁,
            // 当signal 发送通知后,线程解除阻塞同时使用mutex进行加锁
            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;
}

信号量实现生产者与消费者模型

// 信号量的类型 sem_t

int sem_init(sem_t *sem, int pshared, unsigned int value);
    - 功能:初始化信号量
    - 参数:
        - sem : 信号量变量地址
        - pshared : 0 用在线程间,非0用在进程间
        - value : 信号量中的值
// 销毁信号量
int sem_destroy(sem_t *sem);
// 对信号量加锁,调用一次则信号量的值减一, 如果为0, 就阻塞线程
int sem_wait(sem_t *sem);
// 尝试获取信号量
int sem_trywait(sem_t *sem);
// 等待 time 时间
int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
// 解锁信号量,调用一次,信号量加1
int sem_post(sem_t *sem);
int sem_getvalue(sem_t *sem, int *sval);

信号量不保证线程安全问题,需要与互斥量一起使用保证线程安全。

示例5:信号量实现生产者消费者模型

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

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

// 头结点
Node* head = NULL;

pthread_mutex_t mutex;
sem_t psem;     // 生产者与消费者信号量
sem_t csem;

void* producer(void* arg){
    // 生产者创建节点,添加到链表中
    while (1){
        sem_wait(&psem);        // psem--

        // 共享数据加锁
        pthread_mutex_lock(&mutex);

        // 头插法
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->next = head;
        newNode->num = rand() % 1000;
        head = newNode;
        printf("Add node, num: %d, tid: %ld\n", newNode->num, pthread_self());

        // 解锁
        pthread_mutex_unlock(&mutex);
        sem_post(&csem);        // csem++

        usleep(100);
    }
    return NULL;
}

// 
void* customer(void* arg){
    while (1){      
        sem_wait(&csem);

        // 共享数据加锁
        pthread_mutex_lock(&mutex);

        Node* cur = head;
        head = head->next;
        printf("delete node num: %d, tid: %ld\n", cur->num, pthread_self());
        free(cur);

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

int main(){
    // 初始化
    pthread_mutex_init(&mutex, NULL);
    sem_init(&psem, 0, 8);      // 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;
}

一键三连是对我最大的鼓励与支持。欢迎关注编程小镇,每天涨一点新姿势😄。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: 下面是一个简单的基于阻塞队列的生产者消费者模型的 C 语言代码示例: ``` #include <stdio.h> #include <pthread.h> #include <semaphore.h> #define MAX_ITEMS 5 int queue[MAX_ITEMS]; int front = 0; int rear = -1; int count = 0; sem_t empty_sem; sem_t full_sem; pthread_mutex_t queue_mutex; void *producer(void *arg) { int item; while (1) { item = rand() % 100; sem_wait(&empty_sem); pthread_mutex_lock(&queue_mutex); queue[++rear] = item; count++; printf("Produced item: %d\n", item); pthread_mutex_unlock(&queue_mutex); sem_post(&full_sem); } } void *consumer(void *arg) { int item; while (1) { sem_wait(&full_sem); pthread_mutex_lock(&queue_mutex); item = queue[front++]; count--; printf("Consumed item: %d\n", item); pthread_mutex_unlock(&queue_mutex); sem_post(&empty_sem); } } int main() { pthread_t producer_thread, consumer_thread; sem_init(&empty_sem, 0, MAX_ITEMS); sem_init(&full_sem, 0, 0); pthread_mutex_init(&queue_mutex, NULL); pthread_create(&producer_thread, NULL, producer, NULL); pthread_create(&consumer_thread, NULL, consumer, NULL); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); return 0; } ``` 说明:这里使用了两个信号 `empty_sem` 和 `full_sem` 以及一个互斥 `queue_mutex` 来实现生产者消费者间的同步互斥。当队列为空时,消费者线程将等待 `full_sem` 信号;当队列已满时,生产者线程将等待 `empty_sem` 信号队列数据时,使用互斥来保证 ### 回答2: 生产者-消费者模型是一种常见的多线程编程模型,在多线程环境下,由一个或多个生产者线程生成数据并将其放入缓冲区,然后由一个或多个消费者线程从缓冲区中取出数据进行消费。阻塞队列是一个可以自动阻塞或唤醒线程的队列,当队列为空时,消费者线程将被阻塞,直到有生产者线程向队列中放入数据;当队列满时,生产者线程将被阻塞,直到有消费者线程从队列中取出数据。 下面是一个基于C语言的简单生产者-消费者模型,使用阻塞队列实现。 #include <pthread.h> #include <stdio.h> #include <stdlib.h> #define MAX_QUEUE_SIZE 10 typedef struct { int data[MAX_QUEUE_SIZE]; int front; int rear; int count; pthread_mutex_t mutex; pthread_cond_t not_full; pthread_cond_t not_empty; } BlockingQueue; void init_queue(BlockingQueue* queue) { queue->front = 0; queue->rear = 0; queue->count = 0; pthread_mutex_init(&queue->mutex, NULL); pthread_cond_init(&queue->not_full, NULL); pthread_cond_init(&queue->not_empty, NULL); } void enqueue(BlockingQueue* queue, int item) { pthread_mutex_lock(&queue->mutex); while (queue->count >= MAX_QUEUE_SIZE) { pthread_cond_wait(&queue->not_full, &queue->mutex); } queue->data[queue->rear] = item; queue->rear = (queue->rear + 1) % MAX_QUEUE_SIZE; queue->count++; pthread_cond_signal(&queue->not_empty); pthread_mutex_unlock(&queue->mutex); } int dequeue(BlockingQueue* queue) { pthread_mutex_lock(&queue->mutex); while (queue->count <= 0) { pthread_cond_wait(&queue->not_empty, &queue->mutex); } int item = queue->data[queue->front]; queue->front = (queue->front + 1) % MAX_QUEUE_SIZE; queue->count--; pthread_cond_signal(&queue->not_full); pthread_mutex_unlock(&queue->mutex); return item; } void* producer(void* arg) { BlockingQueue* queue = (BlockingQueue*)arg; for (int i = 1; i <= 100; i++) { enqueue(queue, i); printf("Producer produced: %d\n", i); } pthread_exit(NULL); } void* consumer(void* arg) { BlockingQueue* queue = (BlockingQueue*)arg; for (int i = 1; i <= 100; i++) { int item = dequeue(queue); printf("Consumer consumed: %d\n", item); } pthread_exit(NULL); } int main() { BlockingQueue queue; init_queue(&queue); pthread_t producer_thread; pthread_t consumer_thread; pthread_create(&producer_thread, NULL, producer, &queue); pthread_create(&consumer_thread, NULL, consumer, &queue); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); return 0; } 上述代码中,定义了一个BlockingQueue结构体来表示阻塞队列,使用互斥(mutex)和条件变(cond)来实现线程之间的同步互斥生产者线程使用enqueue函数将数据放入队列,消费者线程使用dequeue函数从队列中取出数据。生产者线程生成1到100的数据并放入队列,消费者线程从队列中取出数据并输出。 此模型通过互斥和条件变的配合,实现生产者线程与消费者线程之间的同步,当队列满时生产者线程阻塞等待,当队列空时消费者线程阻塞等待,从而避免了线程间的数据竞争和问题。 ### 回答3: 阻塞队列是一种常用的线同步机制,它提供了安全的生产者-消费者模型。下面是一个使用C语言实现的简单的基于阻塞队列的生产者消费者模型的示例: ```c #include <stdio.h> #include <stdlib.h> #include <pthread.h> #define BUFFER_SIZE 5 typedef struct { int buffer[BUFFER_SIZE]; int size; int in; int out; pthread_mutex_t mutex; pthread_cond_t full; pthread_cond_t empty; } Queue; void produce(Queue* q, int val) { pthread_mutex_lock(&(q->mutex)); while (q->size == BUFFER_SIZE) { pthread_cond_wait(&(q->full), &(q->mutex)); } q->buffer[q->in] = val; q->in = (q->in + 1) % BUFFER_SIZE; q->size++; pthread_cond_signal(&(q->empty)); pthread_mutex_unlock(&(q->mutex)); } int consume(Queue* q) { pthread_mutex_lock(&(q->mutex)); while (q->size == 0) { pthread_cond_wait(&(q->empty), &(q->mutex)); } int val = q->buffer[q->out]; q->out = (q->out + 1) % BUFFER_SIZE; q->size--; pthread_cond_signal(&(q->full)); pthread_mutex_unlock(&(q->mutex)); return val; } void* producer(void* arg) { Queue* q = (Queue*)arg; for (int i = 1; i <= 10; i++) { produce(q, i); printf("Produced: %d\n", i); } pthread_exit(NULL); } void* consumer(void* arg) { Queue* q = (Queue*)arg; for (int i = 1; i <= 10; i++) { int val = consume(q); printf("Consumed: %d\n", val); } pthread_exit(NULL); } int main() { Queue q; q.size = 0; q.in = 0; q.out = 0; pthread_mutex_init(&(q.mutex), NULL); pthread_cond_init(&(q.full), NULL); pthread_cond_init(&(q.empty), NULL); pthread_t producer_thread, consumer_thread; pthread_create(&producer_thread, NULL, producer, (void*)(&q)); pthread_create(&consumer_thread, NULL, consumer, (void*)(&q)); pthread_join(producer_thread, NULL); pthread_join(consumer_thread, NULL); pthread_cond_destroy(&(q.full)); pthread_cond_destroy(&(q.empty)); pthread_mutex_destroy(&(q.mutex)); return 0; } ``` 该示例中,我们定义了一个用于线程间共享的队列结构体,并使用互斥(`mutex`)和条件变(`full`和`empty`)保证了生产者消费者之间的同步生产者通过`produce`函数将数据存入队列中,如果队列已满,则阻塞等待直到有空间可用。消费者通过`consume`函数从队列中取出数据,如果队列为空,则阻塞等待直到有数据可用。在`main`函数中创建了一个生产者线程和一个消费者线程,并使用`pthread_join`函数等待线程执行结束。 该示例中,生产者线程会依次将数值1~10存入队列中,消费者线程会依次从队列中取出数值并打印。通过互斥和条件变的使用,保证了生产者消费者之间的正确同步,避免了生产者在队列已满时继续生产以及消费者在队列为空时继续消费的问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值