vim muter_lock_demo.cpp
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include <vector>
int num = 0;
void *producer(void*){
int time = 10000000;
while(time --){
num += 1;
}
}
void *comsumer(void*){
int time = 10000000;
while(time --){
num -= 1;
}
}
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);
//print("Print in main function: num = %d\n", num);
printf("Print in main function: num = %d\n", num);
return 0;
}
# 安装c++编译工具
yum list gcc-c++
yum install -y gcc-c++.x86_64
g++ -v
# 编译
g++ muter_lock_demo.cpp -o muter_lock_demo.out -lpthread
./muter_lock_demo.out
# 加互斥量
// 初始化
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
// 加锁
pthread_mutex_lock(&mutex);
// 解锁
pthread_mutex_unlock(&mutex);
# 自旋锁
//定义
pthread_spinlock_t spin_lock;
//初始化(在main函数里)
pthread_spin_init(&spin_lock, 0);
//加锁
pthread_spin_lock(&spin_lock);
pthread_spin_unlock(&spin_lock);