线程同步之互斥量

时间:2020-04-07 11:28:50   收藏:0   阅读:73

操作系统编程--线程同步问题

生产者和消费者问题

具体操作

◆ pthread_mutex_t //用于定义线程互斥锁对象
◆ pthread_mutex_lock(&mutex) //上锁操作
◆ pthread_mutex_unlock(&mutex) //开锁操作

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

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

int num = 0;

void *producer(void*){
    int times = 10000000;
    while(times --){ //不加锁操作则会导致出现共享资源不统一问题 即num 最后不为0
        pthread_mutex_lock(&mutex);
        num += 1;
        pthread_mutex_unlock(&mutex);
    }
}

void *comsumer(void*){
    int times = 10000000;
    while(times --){
        pthread_mutex_lock(&mutex);
        num -= 1;
        pthread_mutex_unlock(&mutex);
    }
}


int main(){
    printf("Start in main function.");
    pthread_t thread1, thread2;
    pthread_create(&thread1, NULL, &producer, NULL);
    pthread_create(&thread2, NULL, &comsumer, NULL);
    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
    printf("Print in main function: num = %d\n", num);
    return 0;
}

编译运行

g++ Thread_Mutex.cpp -o Thread_Mutex -lpthread //编译 -lpthread用于连接动态库
./Thread_Mutex //运行

原文:https://www.cnblogs.com/DengSchoo/p/12652263.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!