2016-10-09 35 views
6

考慮下面的程序 -再添計時器上已經運行循環

#include <iostream> 
#include <uv.h> 

int main() 
{ 
    uv_loop_t loop; 
    uv_loop_init(&loop); 

    std::cout << "Libuv version: " << UV_VERSION_MAJOR << "." 
       << UV_VERSION_MINOR << std::endl; 

    int r = 0; 

    uv_timer_t t1_handle; 
    r = uv_timer_init(&loop, &t1_handle); 
    uv_timer_start(&t1_handle, 
     [](uv_timer_t *t) { std::cout << "Timer1 called\n"; }, 0, 2000); 

    uv_run(&loop, UV_RUN_DEFAULT); 

    // second timer 
    uv_timer_t t2_handle; 
    r = uv_timer_init(&loop, &t2_handle); 
    uv_timer_start(&t2_handle, 
     [](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0, 1000); 

    uv_loop_close(&loop); 
} 

第二個定時器手柄是從來沒有在循環中運行,由於循環已經在運行,而「定時器稱爲」從不打印。所以,我想運行它,然後將第二定時器後暫時停止循環 -

.... 
uv_run(&loop, UV_RUN_DEFAULT); 

// some work 

uv_stop(&loop); 
// now add second timer 
uv_run(&loop, UV_RUN_DEFAULT); // run again 
.... 

但是這一次第一環開始與重複運行後沒有工作,可能是因爲後來的行不會被執行計時器。那麼我應該如何爲已經運行的uvloop添加一個新的定時器句柄?

回答

1

你說得對,循環需要停止,才能註冊一個新的句柄。通過在uv_run之後立即調用uv_stop函數無法實現,因爲uv_run需要先返回。它可以通過例如使用句柄回調來停止它來實現。下面是如何使用現有的Timer1句柄完成的一個非常愚蠢的例子。它在第一次運行中正好停止一次循環。

#include <iostream> 
#include <uv.h> 

int main() { 
    uv_loop_t loop; 
    uv_loop_init(&loop); 

    std::cout << "Libuv version: " << UV_VERSION_MAJOR << "." << UV_VERSION_MINOR 
      << std::endl; 

    int r = 0; 

    uv_timer_t t1_handle; 
    r = uv_timer_init(&loop, &t1_handle); 
    *(bool *)t1_handle.data = true; // need to stop the loop 
    uv_timer_start(&t1_handle, 
       [](uv_timer_t *t) { 
        std::cout << "Timer1 called\n"; 
        bool to_stop = *(bool *)t->data; 
        if (to_stop) { 
        std::cout << "Stopping loop and resetting the flag\n"; 
        uv_stop(t->loop); 
        *(bool *)t->data = false; // do not stop the loop again 
        } 
       }, 
       0, 2000); 
    uv_run(&loop, UV_RUN_DEFAULT); 
    std::cout << "After uv_run\n"; 

    // second timer 
    uv_timer_t t2_handle; 
    r = uv_timer_init(&loop, &t2_handle); 
    uv_timer_start(&t2_handle, 
       [](uv_timer_t *t) { std::cout << "Timer2 called\n"; }, 0, 
       1000); 
    std::cout << "Start loop again\n"; 
    uv_run(&loop, UV_RUN_DEFAULT); 

    uv_loop_close(&loop); 
} 

所以輸出

Libuv version: 1.9 
Timer1 called 
Stopping loop and resetting the flag 
After uv_run 
Start loop again 
Timer2 called 
Timer2 called 
Timer1 called 
Timer2 called 
Timer2 called 
Timer1 called 
+0

涼爽,所以我們可以操縱循環中它的回調函數,只是確保我們首先停止它。 –