Boost.Thread , , David . :
- . .
- If you create only one stream from a specific functor, then the functor may contain a common intelligent pointer to dynamically allocated existing code, which can then be read by the original functor object.
The following are examples of each method:
Method 1:
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
struct thread_alarm
{
thread_alarm(int secs, int &ec) : m_secs(secs), exit_code(ec) { }
void operator()()
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += m_secs;
boost::thread::sleep(xt);
std::cout << "alarm sounded..." << std::endl;
exit_code = 0xDEADBEEF;
}
int m_secs;
int &exit_code;
};
typedef boost::shared_ptr<boost::thread> BoostThreadPtr;
int main(int argc, char* argv[])
{
int secs = 1;
int exit_codes[10];
BoostThreadPtr threads[10];
for (int i = 0; i<10; ++i) {
std::cout << "setting alarm for 1 seconds..." << std::endl;
thread_alarm alarm(secs, exit_codes[i]);
threads[i] = BoostThreadPtr(new boost::thread(alarm));
}
for (int i = 0; i<10; ++i) {
threads[i]->join();
std::cout << "exit code == 0x" << std::hex << exit_codes[i] << std::endl;
}
}
Method 2:
#include <boost/thread/thread.hpp>
#include <boost/thread/xtime.hpp>
#include <boost/shared_ptr.hpp>
#include <iostream>
struct thread_alarm
{
thread_alarm(int secs) : m_secs(secs) { exit_code = IntPtr( new int(0) ); }
void operator()()
{
boost::xtime xt;
boost::xtime_get(&xt, boost::TIME_UTC);
xt.sec += m_secs;
boost::thread::sleep(xt);
std::cout << "alarm sounded..." << std::endl;
*exit_code = 0xDEADBEEF;
}
int m_secs;
typedef boost::shared_ptr<int> IntPtr;
IntPtr exit_code;
};
int main(int argc, char* argv[])
{
int secs = 5;
std::cout << "setting alarm for 5 seconds..." << std::endl;
thread_alarm alarm(secs);
boost::thread thrd(alarm);
thrd.join();
std::cout << "exit code == 0x" << std::hex << *(alarm.exit_code) << std::endl;
}
source
share