从boost :: thread获取退出代码的标准方法是什么? The docs似乎根本没有涉及这个主题。
答案 0 :(得分:5)
POSIX不支持线程返回代码。我建议您使用未来:C++11 provides futures in the standard library,或者如果您使用的是较旧版本的C ++,则Boost.Thread library已经很好地实现了期货since version 1.41。这为您提供了阻塞和非阻塞通信的通用语法,允许您返回任何类型的对象,并且因为锦上添花允许您将异常传播出线程。
答案 1 :(得分:1)
由于Boost.Thread会复制您传递的仿函数,因此David的解决方案无法在任何实际示例中使用。你基本上有两个选择:
以下是每种方法的示例:
方法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;
}
}
方法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;
}
答案 2 :(得分:-1)
我不知道线程退出代码是否可用作特定于操作系统的代码。您可以通过执行以下操作来模拟传递退出代码或结果代码:
struct callable {
int result;
void operator()()
{
result = 42;
}
};
void process_on_thread() {
callable x;
boost::thread processor(x);
processor.join();
int result = x.result;
}