C ++,XCode 4.6.3,OSX 10.8.2,在iOS上部署
我正在尝试创建一个定时事件。
我的思路是创建一个线程,在其中进行计时,然后在结束时调用另一个函数。这可以工作,但会暂停程序的其余部分。
//Launch a thread
std::thread t1(start_thread);
//Join the thread with the main thread
t1.join();
void start_thread()
{
std::cout << "thread started" << std::endl;
auto start = std::chrono::high_resolution_clock::now();
std::this_thread::sleep_until(start + std::chrono::seconds(20));
stop_thread();
}
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
}
有没有一种不会暂停程序执行的方法来做到这一点?
更新:
我可以在头文件中声明线程,并在stop_thread()中加入线程:
void stop_thread()
{
std::cout << "thread stopped." << std::endl;
ti.join();
}
但会抛出以下错误:
'std::thread'类型不提供调用运算符
更新2:调用t1.detach()代替join似乎可以正常工作。
join
函数,至少在你完成了想要在这20秒内做的任何事情之前不要调用。join
会阻塞你的主线程。 - Igor Tandetnikstd::thread t1
移动到头文件中,并将ti.join()
放在stop_thread()
中,但这会使我面临t1(start_thread);
的问题,因为它会抛出一个关于未提供函数调用的错误。 - Jasminedetach()
能够让结果不必回到主线程,仅仅触发某个事件即可,但这种方式仍然可行。 - Jasmine