多线程与线程锁的记录


前言

c++多线程与线程锁的记录。


提示:以下是本篇文章正文内容,下面案例可供参考

一、多线程

多线程是指在一个程序中同时运行多个不同的线程来执行不同的任务。这些线程是程序中的独立执行流,每个线程都有自己的专有寄存器(如栈指针、程序计数器等),但代码区是共享的。利用多线程技术,可以提高程序的运行效率和资源利用率。(但是使用多线程有时会导致一些问题,需要处理的数据不大时尽可能别用。)

二、线程的使用

1.创建线程并运行

代码如下(示例):

#include <iostream>  
#include <thread>  
#include <mutex>  
#include <chrono>  


using namespace std;
int sum = 20;
mutex mtx;
void print_even_increment(int n) {
    for (int i = 1; i <= n; i++) {
        
        cout << "当前余票:" << sum << "张     ";
        sum -= 1;
        cout << "购买成功,当前余票:" << sum << " 购买者为:" << this_thread::get_id() << "购买了1张" << endl;
        this_thread::sleep_for(chrono::milliseconds(100)); // 模拟耗时操作  
    }
    cout << '\n';
}

void print_even_with_cost(int n, int cost) {
    for (int i = 1; i <= n; i++) {
        cout << "当前余票:" << sum << "张    ";
        sum -= cost;
        cout << "购买成功,当前余票:" << sum << " 购买者为:" << this_thread::get_id() << "购买了" << cost << "张" << endl;
        this_thread::sleep_for(chrono::milliseconds(100)); // 模拟耗时操作  
    }
    cout << '\n';
}

int main() {
    thread th1(print_even_increment, 20);
    thread th2(print_even_with_cost, 20, 2);
    th1.join();
    th2.join();

    return 0;
}

这里创建了两个线程去执行两个任务,他们共享资源sum,每一个任务都可以修改sum会导致输出结果混乱。具体如何混乱这里不在赘述,自己可以去跑一下。

2.线程锁

线程锁就是为了解决上述问题的一个方案。概念不在赘述。
代码如下(示例):

#include <iostream>  
#include <thread>  
#include <mutex>  
#include <chrono>  


using namespace std;
int sum = 99;
mutex mtx;
void print_even_increment(int n) {
    for (int i = 1; i <= n; i++) {
       /* if (sum <= 0)
            return;*/
        unique_lock<std::mutex> lck(mtx);
        cout << "当前余票:" << sum << "张     ";
        sum -= 1;
        cout << "购买成功,当前余票:" << sum << " 购买者为:" << this_thread::get_id() << "购买了1张"<< endl;
        lck.unlock();
        this_thread::sleep_for(chrono::milliseconds(100)); // 模拟耗时操作  
    }
    cout << '\n';
}

void print_even_with_cost(int n, int cost) {
    for (int i = 1; i <= n; i++) {
        /*if (sum <= 2)
            return;*/
        unique_lock<std::mutex> lck(mtx);
        cout << "当前余票:" << sum << "张    ";
        sum -= cost;
        cout << "购买成功,当前余票:" << sum << " 购买者为:" << this_thread::get_id() <<"购买了"<<cost<<"张" << endl;
        this_thread::sleep_for(chrono::milliseconds(100)); // 模拟耗时操作  
    }
    cout << '\n';
}

int main() {
    thread th1(print_even_increment, 5);
    thread th2(print_even_with_cost, 5, 2);
    th1.join();
    th2.join();

    return 0;
}

如果还是不太理解的话可以把两部分代码分别运行,看看现象。


  • 12
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值