【发布时间】:2011-09-01 20:35:26
【问题描述】:
我想了解以下代码是否正确
#include <iostream>
#include <boost/thread/thread.hpp>
#include <vector>
using namespace std;
using namespace boost;
class background_task
{
private:
std::vector<int> numbers;
public:
background_task()
{
i=0;
numbers.assign(6000,0);
}
void someLongComputation()
{
while (++i<200)
{
//boost::mutex::scoped_lock(formutex);
// cout << "Thread inside: i= " << this->i << endl;
numbers.at(0)=i;
cout << "Thread inside numbers= " << numbers.at(0) << endl;
boost::this_thread::sleep(boost::posix_time::milliseconds(100));
}
}
std::vector<int>& getNumbers()
{
return numbers;
}
int i;
};
background_task f;
void valuePicker()
{
int j=0;
while ( (j++) < 20 )
{
boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
cerr << "First number= " << f.getNumbers().at(0) << endl;
}
}
int main(void)
{
boost::thread comp(boost::bind(&background_task::someLongComputation, &f));
boost::thread value(valuePicker);
comp.join();
return 0;
}
这段代码应该启动两个线程:一个执行 someLongComputation(我添加了一个计时器休眠器来模拟实际上非常短的 loooong 计算),另一个线程以不同的频率访问计算线程中包含的数据。
我现在想知道这种方法是否正确,因为在我看来不需要互斥锁,我想问你如何使这段代码更加线程安全和正确,因为我想我错过了一些东西.. .
传递一个非常量引用是正确的还是应该更安全地使其成为常量? 创建的数据不应该被写入,只能被读取......
谢谢!我希望通过这个线程最终解决我的初学者对多线程问题的疑虑......
【问题讨论】:
-
线程安全不是以度数来衡量的
标签: multithreading boost asynchronous mutex pass-by-reference