C++定时器暂停程序的执行直到完成



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.destrict()而不是join似乎有效。

你说得对,它有效:以下是来自cpp引用的一个示例http://en.cppreference.com/w/cpp/thread/thread/detach

#include <iostream>
#include <chrono>
#include <thread>
void independentThread() 
{
    std::cout << "Starting concurrent thread.n";
    std::this_thread::sleep_for(std::chrono::seconds(2));
    std::cout << "Exiting concurrent thread.n";
}
void threadCaller() 
{
    std::cout << "Starting thread caller.n";
    std::thread t(independentThread);
    t.detach();
    std::this_thread::sleep_for(std::chrono::seconds(1));
    std::cout << "Exiting thread caller.n";
}
int main() 
{
    threadCaller();
    std::this_thread::sleep_for(std::chrono::seconds(5));
}

输出:正在启动线程调用程序。正在启动并发线程。正在退出线程调用程序。正在退出并发线程。

我们看到并发线程在线程调用程序结束之后结束。如果未调用分离,则这是不可能的。

希望这能有所帮助,但杰森找到了解决方案。

请改用类。

enum{ PAUSED, STARTED, STOPPED };
class AsyncEvent
{
protected:
    unsigned char mState;
public:
    AsyncEvent():mState(PAUSED){ mThread = std::thread(&AsyncEvent::run,this); }
    ~AsyncEvent(){ mThread.join(); }
private:
    std::thread mThread;
    void run()
    {
        std::cout << "thread started" << std::endl;
        while(mState != STOPPED)
        {
            if(mState == PAUSED)break;
            auto start = std::chrono::high_resolution_clock::now();
            std::this_thread::sleep_until(start + std::chrono::seconds(20));
        }
    }
    void stop()
    {
        mState = STOPPED;
    }
    void pause()
    {
        mState = PAUSED;
    }
};