으로 부스트 1.49와 MSVC10을 사용하고 있습니다. boost::thread
하면호출 가능한 객체에 액세스하기 boost :: thread가 생성되었습니다
는 호출 객체 1로 구성되고, 나는 callabe 객체에 도착 어떻게 그 객체는 멤버 함수 또는 나는 thread
의 컨텍스트 외부 에서 액세스 할 변수가?
예를 들어 main()
에 로컬 인 vector<boost::thread*>
에 저장된 5 개의 작업자 스레드를 생성하는 간단한 응용 프로그램을 구현했습니다. 이 스레드들 각각은 생성자에 char
매개 변수 하나를 취하는 호출 가능 객체 Gizmo
으로 인스턴스화됩니다. 이 char
은 Gizmo
클래스에 std::string
멤버 변수로 저장됩니다. 각 스레드는 cout
으로 저장되고 string
으로 저장되고 250ms 동안 잠자기됩니다. 어쨌든 의 값이 "죽습니다"가 될 때까지 계속이 루프에서 영원히 계속됩니다.
Short, Self Contained, (Hopefully) Correct, Example :
이- 가
vector
- 의 첫
thread
가Gizmo
객체가thread
에 포함하기하기 :#include <cstdlib> #include <string> #include <memory> #include <vector> using namespace std; #include <boost/thread.hpp> #include <boost/date_time/posix_time/posix_time.hpp> boost::mutex cout_mtx; class Gizmo { public: Gizmo(const string& state) : state_(state) {}; Gizmo(Gizmo&& rhs) : state_(std::move(rhs.state_)) {}; virtual ~Gizmo() { bool b = true; } void operator()(); string state_; }; void Gizmo::operator()() { while(state_ != "die") { { boost::mutex::scoped_lock scoped_lock(cout_mtx); cout << state_ << flush; } boost::this_thread::sleep(boost::posix_time::milliseconds(250)); } } boost::thread* start_thread(char c) { Gizmo g(string(1,c)); return new boost::thread(g); } int main() { vector<boost::thread*> threads; string d=".*x%$"; for(string::const_iterator it = d.begin(); it != d.end(); ++it) { threads.push_back(start_thread(*it)); } for(auto th = threads.begin(); th != threads.end(); ++th) (*th)->join(); }
지금 나는 것
main()
의 코드 변경을 만들고 싶어 - 세트
state_
"die"
스레드 내에서 Gizmo
을 얻으려면 어떻게해야합니까? 이러한 맥락에서
for(auto th = threads.begin(); th != threads.end(); ++th)
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
Gizmo& that_gizmo = (*th)-> ??? ; // WHAT DO I DO?
that_gizmo.state_ = "die";
}
(1) 호출 객체는 operator()
와 class
을 의미한다.
이 클로리는 내 마지막 솔루션과 흡사합니다. –