Boost线程:释放后被修改的对象

boost thread: object modified after being freed

本文关键字:修改 对象 线程 释放 Boost      更新时间:2023-10-16

我试图创建一个简单的多线程应用程序与boost线程。基本上,我必须计算大约100个东西,并希望一次将其拆分为8个线程。唯一棘手的方面是,我需要传递一个指针给工人,然后获得一些返回值。在下面的例子中,指针只是一个浮点数,但在我的实际应用程序中,它是一个更大的类。这段错误。我做错了什么?

EDIT作为独立文件写入:

#include <iostream>
#include <vector>
#include <boost/thread.hpp>
using namespace std;
class Worker {
public:
  Worker(boost::atomic<int> & threads,
         boost::mutex & mutex,
         boost::condition_variable & condition):
    threads_(threads), mutex_(mutex), condition_(condition){}
  void do_stuff(int num, float * num2){
    results_.reserve(num);
    for (int i=0;i<num;i++){
      results_.push_back(*num2);
    }
    boost::mutex::scoped_lock lock(mutex_);
    threads_--;
    condition_.notify_one();
  }
  std::vector<float> results_;
private:
  boost::atomic<int> & threads_;
  boost::mutex & mutex_;
  boost::condition_variable & condition_;
};
int main(){
  int ntasks = 25;
  std::vector<Worker> workers;
  workers.reserve(ntasks);
  boost::thread_group thread_group;
  boost::mutex mutex;
  boost::condition_variable condition;
  boost::atomic<int> threads(0);
  float * bean;
  *bean = 3.14159;
  for(int iz=0;iz<ntasks;iz++){
    boost::mutex::scoped_lock lock(mutex);
    while (threads >= 8) condition.wait(lock);
    Worker w = Worker(threads, mutex, condition);
    workers.push_back(w);
    boost::function<void()> th_func = boost::bind(&Worker::do_stuff,
                                                  &workers.back(),5,bean);
    boost::thread * thread = new boost::thread(th_func);
    thread_group.add_thread(thread);
    threads++;
  }
  thread_group.join_all();
  //inspect the results
  for (int iw=0;iw<workers.size();iw++){
    for (int it=0;it<5;it++){
      cout<<workers[iw].results_[it]<<" ";
    }
    cout<<endl;
  }
  return 0;
}

在我的mac上编译成:

g++ test.cpp -o thread -I/usr/local/include -L/usr/local/lib -lboost_thread-mt -lboost_system-mt

如果您有*bean = 3.14159; bean不指向任何东西,则需要首先分配bean(而不是*bean)一个值。试试

float beanValue;
float *bean = &beanValue;
*bean = 3.14159;