이
int i = 10;
auto pred = [i]() mutable {return i--;};
auto print = []{cout << "." << endl;};
timer t{500ms};
t.push({print, pred}); //asynchronously prints '.' 10 times within 5s
//do anything else
가정 성능이 중요하지 않고 타이머가 종종 충분한 기능을 제공해야 다음, 업데이트되지 않습니다이다.
#include<functional>
#include<vector>
#include<thread>
#include<utility>
#include<chrono>
#include<mutex>
#include<atomic>
class timer final
{
public:
using microseconds = std::chrono::microseconds;
using predicate = std::function<bool()>;
using callback = std::function<void()>;
using job = std::pair<callback, predicate>;
explicit timer(microseconds t) : done{false}, period{t}
{
std::lock_guard<std::mutex> lck(mtx);
worker = std::thread([this]{
auto t = std::chrono::steady_clock::now();
while(!done.load())
{
std::this_thread::sleep_until(t);
std::lock_guard<std::mutex> lck(mtx);
t += period;
for(auto it = jobs.begin(); it != jobs.end();)
{
if(it->second())
it++->first();
else
it = jobs.erase(it);
}
}
});
}
~timer()
{
done.store(true);
worker.join();
}
void set_period(microseconds t)
{
std::lock_guard<std::mutex> lck(mtx);
period = t;
}
void push(const callback& c)
{
std::lock_guard<std::mutex> lck(mtx);
jobs.emplace_back(c, []{return true;});
}
void push(const job& j)
{
std::lock_guard<std::mutex> lck(mtx);
jobs.push_back(j);
}
private:
std::mutex mtx;
std::atomic_bool done;
std::thread worker;
std::vector<job> jobs;
microseconds period;
};
timer
호출 이전에 주기적으로 callback
들 기선을 제압 당했지만, predicate
이 false
로 평가하면, timer
에서 callback
을 삭제합니다. timer
개체는 자체 수명을 가지며 작업자 스레드는 그것이 살아있는 동안 만 살아갑니다.
timer
에 복수의 job
을 넣고 싶은 이유는 하나의 스레드 만 사용하여 함께 호출되고 서로 동기화되기 때문입니다.
는 타이머를> 10,000 회 초를 업데이트 할 계획하지 않는 한 mutex
걱정 <이 1ms의 기간이 있거나 매우 많은 시간이 소요 callback
의이 없습니다.
프로그램이 다른 작업을 수행하는 동안 타이머가 비동기 적으로 작동하게 하시겠습니까? 그런 다음 내부 스레드를 시간 지정 프로세스에 넣어야합니다. –
@JasonLang 물론 그 자체의 스레드 – towi
'ping (100ms, callback)'행을 따라 뭔가를 원한다는 것을 의미합니까? –