我正在尝试使用boost线程创建一个简单的多线程应用程序。基本上我必须计算大约100个东西,并希望一次将它分成8个线程。唯一棘手的方面是我需要将指针传递给worker,然后获取一些返回值。在下面的例子中,指针只是一个浮点数,但在我的实际应用程序中,它是一个更大的类。这段错误。我做错了什么?
编辑写为独立文件:
#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
答案 0 :(得分:0)
如果*bean = 3.14159;
bean
没有指向任何内容,则需要先为bean
(而不是*bean
)分配值。尝试像
float beanValue;
float *bean = &beanValue;
*bean = 3.14159;