gpt4 book ai didi

c++ - 使用命令文件在线程之间传递消息

转载 作者:行者123 更新时间:2023-11-28 06:34:55 25 4
gpt4 key购买 nike

这个项目需要 4 个线程,它们有一个命令文件 SEND、Receive 和 quit 等指令。当文件显示“2 发送”数组中第二位应该唤醒的线程 起来并接收它的消息。我需要知道如何让线程读取 如果命令文件有消息,它是消息吗?

最佳答案

我在您的设计中看到的最大问题是每个线程独立于任何其他线程随机读取其行。在此之后,它必须检查当前行是否真的适用于它,即从适当的数字开始。如果不是会怎样?太复杂。

我会把这个问题分成一个读者线程和一组工作线程。第一个从文件中读取行并通过将其插入当前工作队列来将其分派(dispatch)给工作人员。全部与每个工作人员互斥锁和条件变量同步以下是在 C++11 中实现的,但也应该以 pthread_* 样式实现。

#include <thread> 
#include <iostream>
#include <queue>
#include <mutex>
#include <fstream>
#include <list>
#include <sstream>
#include <condition_variable>

class worker {
public:
void operator()(int n) {
while(true) {
std::unique_lock<std::mutex> l(_m);
_c.wait(l);
if(!_q.empty()) {
{
std::unique_lock<std::mutex> l(_mm);
std::cerr << "#" << n << " " << _q.back() <<std::endl;
}
_q.pop();
}
}
}
private:
std::mutex _m;
std::condition_variable _c;
std::queue<std::string> _q;
// Only needed to synchronize I/O
static std::mutex _mm;
// Reader may write into our queue
friend class reader;
};

std::mutex worker::_mm;

class reader {
public:
reader(worker & w0,worker & w1,worker & w2,worker & w3) {
_v.push_back(&w0);
_v.push_back(&w1);
_v.push_back(&w2);
_v.push_back(&w3);
}
void operator()() {
std::ifstream fi("commands.txt");
std::string s;

while(std::getline(fi,s)) {
std::stringstream ss(s);
int n;
if((ss >> n >> std::ws) && n>=0 && n<_v.size()) {
std::string s0;
if(std::getline(ss,s0)) {
std::unique_lock<std::mutex> l(_v[n]->_m);
_v[n]->_q.push(s0);
_v[n]->_c.notify_one();
}
}
}

std::cerr << "done" << std::endl;
}
private:
std::vector<worker *> _v;

};

int main(int c,char **argv) {

worker w0;
worker w1;
worker w2;
worker w3;

std::thread tw0([&w0]() { w0(0); });
std::thread tw1([&w1]() { w1(1); });
std::thread tw2([&w2]() { w2(2); });
std::thread tw3([&w3]() { w3(3); });

reader r(w0,w1,w2,w3);

std::thread tr([&r]() { r(); });

tr.join();
tw0.join();
tw1.join();
tw2.join();
tw3.join();
}

示例代码仅从“commands.txt”读取直到 EOF。我假设您喜欢像“tail -f”命令一样连续阅读。然而,这对于 std::istream 是不可行的。

当然代码很笨拙,但我想它给了你一个想法。例如,如果工作人员处理他们的东西太慢并且队列可能会耗尽所有宝贵的 RAM,则应该添加一种阻塞机制。

关于c++ - 使用命令文件在线程之间传递消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26924588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com