首页 > 解决方案 > 使用共享队列的 Cpp Contentfunction 线程外

问题描述

使用 python 后,我刚刚开始再次使用 cpp。我有一个关于线程的问题。设置:创建包含消费者函数和生产者函数的对象的主要方法。我想将它们作为两个线程或三个线程相互独立地运行,以供额外的消费者或生产者使用。(见。类)。从设置中我想我理解了线程的主题但是我不明白我得到的错误,因为我不太习惯 cpp 线程。

错误:

错误 C2893: Funktionsvorlage "unknown-type std::invoke(_Callable &&,_Types &&...) noexcept()" konnte nicht spezialisiert werden xthread(237): 注意: Mit den folgenden Vorlagenargumenten:

xthread(237): 注意:“_Callable=void (__thiscall Worker_Consumer::*)(std::mutex &,std::condition_variable &,std::deque> &)”

xthread(237): 注意:“_Types={std::mutex *, std::condition_variable *, std::deque> *}”

#include "pch.h"
#include <iostream>
#include "CAN_MESSAGE.h"
#include <bitset>
#include <thread>
#include "Worker_Consumer.h"
#include <mutex>
#include <condition_variable>
#include <chrono>


int main()
{
    //sendMessage();
    std::deque<int> sharedQ;
    mutex mtx;
    condition_variable convar;

    std::thread t1(&Worker_Consumer::startProducer,&mtx,&convar, &sharedQ);
    std::thread t2(&Worker_Consumer::startConsumer,&mtx, &convar, &sharedQ);

    t1.join();
    t2.join();
}

以及我的头文件(只是为了测试我直接在里面编码)。

#pragma once
#include <mutex>
#include <thread>
#include <condition_variable>
#include <iostream>
#include <deque>
using namespace std;

class Worker_Consumer {

private:
    int WORKER_ID = 0;
    int TRIGGER = 0;
    bool is_running1 = false;
    bool is_running2 = false;

public:
    //PRODUCER
    void startProducer(mutex &mtx, condition_variable &convar, std::deque<int> &sharedQ) {
        this->is_running1 = true;
        int count = 10;
        while (count > 0) {
            std::unique_lock<mutex> locker(mtx);
            sharedQ.push_front(count);
            locker.unlock();
            convar.notify_one(); //wakes up thread2
            std::this_thread::sleep_for(chrono::seconds(1));
            count--;
        }
        this->is_running1 = false;

    }
    //CONSUMER
    void startConsumer(mutex &mtx, condition_variable &convar, std::deque<int> &sharedQ) {
        this->is_running2 = true;
        int data = 0;
        while (data != 1) {
            std::unique_lock<mutex>locker(mtx);
            convar.wait(locker);
            data = sharedQ.back();
            sharedQ.pop_back();
            locker.unlock();
            cout << "t2 got a value from t1:" << data << endl;
            }
        this->is_running2 = false;
    }

    bool isActive1() {
        return this->is_running1;
    }

    bool isActive2() {
        return this->is_running2;
    }
    //DEKLARATION VON GETTERN FUER KONSTANTEN
    Worker_Consumer() {
    }
};

THX 和贪婪

标签: multithreadingvisual-c++member-functions

解决方案


推荐阅读