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

在这里插入图片描述

发布了105 篇原创文章 · 获赞 24 · 访问量 5万+

猜你喜欢

转载自blog.csdn.net/Kwansy/article/details/104470196