[英]C++ Timer pausing execution of program until finished
在iOS上部署的C ++,XCode 4.6.3,OSX 10.8.2
我正在嘗試創建一個定時事件。
我的思維過程是創建一個線程,在其中執行時間,然后在最后讓它調用另一個函數。 這是有效的,但它暫停了程序的其余部分。
//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似乎工作。
你是對的嗎:這是一個來自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;
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.