操作系统编程--线程同步问题
生产者和消费者问题
-
互斥量是最简单的线程同步的方法
-
互斥量(互斥锁),处于两态之一的变量:解锁和加锁
-
两个状态可以保证资源访问的串行
-
操作系统直接提供了互斥量的API
-
开发者可以直接使用API完成资源的加锁、解锁操作
具体操作
◆ 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 //运行