c++11 多线程传参和生产者消费者实现

普通函数传参和成员函数传参

#include <iostream>
#include <thread>
#include <windows.h>
void func(int x) {
    for (int i = 1; i <= 10; i++) {
        printf("%d\n", x);
        Sleep(100);
    }
}

class A{
public:
    void func(int x) {
        for (int i = 1; i <= 10; i++) {
            printf("%d\n", 2);
            Sleep(100);
        }
    }
};
int main() {
    A a;
    std::thread(&A::func, &a, 2).detach(); // 成员函数多线程这样写
    std::thread(func, 1).detach();

    getchar(); // 如果主进程结束那么子线程也会死
    return 0;
}

在这里插入图片描述

生产者消费者

#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <windows.h>

std::vector<int> data; // 临界区
std::mutex mux; // 全局互斥锁

/**
“生产者-消费者”问题的实现,我的理解是:通过竞争互斥锁来间接实现对临界区的互斥访问。
同一时间段内,只有一个线程得到了 mux 互斥锁,那么接下来对临界区的操作自然也是互斥的,直到释放这个互斥锁。
**/
void product_thread(){
    while(true){
        std::unique_lock<std::mutex> lock(mux);
        if (data.size() >= 5) {
            lock.unlock();
            continue;
        }
        data.push_back(1);
        printf("----生产\n");
        lock.unlock();
        Sleep(200);
    }
}

void consume_thread(){
    while (true){
        std::unique_lock<std::mutex> lock(mux);
        if(data.empty()) {
            lock.unlock();
            continue;
        }
        printf("消耗\n");
        data.pop_back();
        lock.unlock();
        Sleep(1000);
    }
}

int main() {
    std::thread thread_product(&product_thread);
    std::thread thread (&consume_thread);
    thread_product.join();
    thread.join();

    return  0;
}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值