multithreading - 使用共享队列的 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 和贪婪
解决方案
推荐阅读
- java - testcontainers - 由于测试失败,Maven 构建失败
- dataframe - 如何在 pyspark 数据框中将时间戳转换为 bigint
- graph - 将图形编辑距离标准化为 [0,1] (networkx)
- c++ - 创建链表,但不能按 cpp 的预期工作
- python - 查找最后一个整数并返回变量名
- python - 我可以做出改变来避免 SVR 中的负 R2 分数吗?
- html - 使用 css 定位 fontawesome 图标
- c# - 如何将图像绑定到嵌套图像的网格具有不同绑定上下文的列表?
- python - Python列表如何再次从最后一个到第一个?
- node.js - db-migrate 从 csv 插入数据