나는 다음과 같은 코드가스레드 현대 접근
#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 계산을 시뮬레이션하기 위해 타이머 침대를 추가 실제로는 매우 짧음)와 계산 스레드에 포함 된 데이터와 다른 빈도로 액세스하는 다른 스레드가 있습니다.
mutexes가 필요하지 않은 것처럼 보이기 때문에이 접근법이 올바른지 궁금합니다. 뭔가 빠뜨린 것 같아서이 코드를 스레드로부터 안전하고 올바르게 만드는 방법을 묻습니다. ..
const가 아닌 참조를 전달하는 것이 맞습니까? 아니면 const로 만드는 것이 더 안전합니까? 작성된 데이터는 쓰여서는 안되며 읽기 전용입니다 ...
고마워요! 이 쓰레드로 마침내 멀티 쓰레딩에 대한 나의 초보자들의 의구심을 해결할 수 있기를 바랍니다 ...
스레드 안전성은 수치로 측정되는 것이 아닙니다 –