线程同步之互斥量和自旋锁

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值