【问题标题】:std::queue does not keep datastd::queue 不保存数据
【发布时间】:2015-05-01 15:21:22
【问题描述】:

这是我的两个课程:

class App {
public:
  void run(){
    std::vector < std::thread > th_list;
    for(std::vector < Host * > ::iterator it = host_list.begin(); it != host_list.end(); it++){
      th_list.push_back(std::thread(&App::th_getInfo, *this, *it, readFile(holder["cmdFile"])));
    }

    for(std::vector<std::thread>::iterator it = th_list.begin(); it != th_list.end(); it++){
      it->join();
    }
  }
private:
  void th_getInfo(Host * pc, std::string info){
    std::string result;
    if(pc->query(info, &result)){
      holder.Push(pc->getIp(), result);
    }
  }


  std::vector < Host * > host_list;
  Holder holder;
};

class Holder {
public:
  void Push(std::string ip, std::string data){
    _m.lock();
    std::pair <std::string, std::string> tmp(ip, data);
    q.push(tmp);
    std::cout << q.size() << std::endl;
    _m.unlock();
  }
  inline std::string &operator[] (std::string j){ return config[j]; }
private:
  std::map <std::string, std::string> config;
  std::mutex _m;
  std::queue < std::pair < std::string, std::string> > q;
}

所以,我的问题是每次调用函数 Holder::Push q.size() 在开始时等于 0,在函数结束时等于 1。推送的对象消失了,但我不调用 q.pop()。

【问题讨论】:

  • 推送前是否通过值传递HolderApp?请创建Minimal, Complete, and Verifiable Example 并向我们展示您如何使用这些课程。另外请告诉我们您是如何检查前后没有物品的。
  • @JoachimPileborg 抱歉,我不明白您所说的“按价值传递”是什么意思。
  • 如果你把一个对象按值传递给一个函数,它是复制的,不管你对副本做了什么改变,它仍然是对副本做的并且不会' t 反映在原始对象中。
  • 好的,我知道。我之前没有通过HolderAppholder 属于 App 类。而queue q 是它的字段。

标签: c++ queue


【解决方案1】:

我认为这是你的问题:

th_list.push_back(std::thread(&App::th_getInfo, *this, *it, readFile(holder["cmdFile"])));

std::thread 按值接受参数;所以 *this 会创建一个 App 对象的副本,并带有一个单独的 Holder。您可以通过如下包装获得参考语义,正如您和上帝所期望的那样:

th_list.push_back(std::thread(&App::th_getInfo, std::ref(*this), *it, readFile(holder["cmdFile"])));

类似问题请见here;在您的应用的复制构造函数中放置一个调试打印,您应该会看到每次创建线程时都会调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-18
    • 2022-01-20
    • 1970-01-01
    • 2011-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多