Boost线程:释放后被修改的对象
boost thread: object modified after being freed
我试图创建一个简单的多线程应用程序与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;
相关文章:
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 使用可变允许修改unordered_set中的对象
- 未定义的对象(〔basic.life〕/8):为什么允许引用重新绑定(和常量修改)
- 如何修改函数中的对象?
- 通过引用在矢量中放置和修改对象
- 为什么我可以通过原始指针而不是shared_ptr来修改对象
- const 方法使用引用修改对象
- 在C 向量中修改对象值的麻烦
- 修改对象也会修改同一类的所有其他对象
- SFML-无法在窗口中修改对象
- 如何使用 *& 修改对象 C++
- 修改对象与修改该对象的副本
- 指针指向矢量调用的方法无法修改对象
- 带函子修改对象的Const函数
- 如何在构造函数中初始化的函数中修改对象大小的2D向量
- 从复制构造函数外部修改对象成员时导致向量内存损坏,但从复制构造函数内部修改时不会
- 如何在不调用成员函数的情况下修改对象
- visualstudio 2012-如何在c++中修改对象已知内存地址
- 在集合内修改对象的可变成员是否安全