如果要使用www.ideone.com运行此程序
#include <iostream>
#include <thread>
#include <utility>
#include <stdexcept>
class scoped_thread
{
private:
std::thread t;
public:
explicit scoped_thread( std::thread t ) : t( std::move( t ) )
{
if ( not this->t.joinable() )
{
throw std::logic_error( "No thread" );
}
}
~scoped_thread()
{
t.join();
}
scoped_thread( const scoped_thread & ) = delete;
scoped_thread & operator =( const scoped_thread & ) = delete;
};
void h()
{
std::cout << "h() is running\n";
for ( size_t i = 0; i < 10000; i++ );
std::cout << "exiting h()\n";
}
void f()
{
scoped_thread t( std::thread( h ) );
}
int main()
{
f();
std::thread t( h );
t.join();
return 0;
}那么输出是
h() is running
exiting h()它对应于main中启动的线程t。
但是,没有来自使用类scoped_thread启动的线程的simialr输出。为什么?
发布于 2018-03-30 12:58:44
scoped_thread t( std::thread( h ) );这定义了一个函数t,它使用一个名为h的std::thread并返回一个scopted_thread。要实际声明对象,请声明:
scoped_thread t{ std::thread(h) };https://stackoverflow.com/questions/49574748
复制相似问题