簡體   English   中英

APR線程和信號處理

[英]APR threads and signal handling

我目前正在嘗試使用Apache Portable Runtime實現線程。 一切正常,除非我不確定我是否按照預期的方式進行操作,因為缺少文檔或示例。

我需要兩個線程和信號處理來捕獲控制台上的CTRL-C來清理我的服務器和可能的線程。 這是我目前的做法:

// Define APR thread pool
apr_pool_t *pool;

// Define server
MyServer *server;

// Define threads
apr_thread_t *a_thread, *b_thread;
apr_status_t status;

static void * APR_THREAD_FUNC func_a(apr_thread_t * thread,
        void *data) {
        // do func_a stuff here
}

static void * APR_THREAD_FUNC func_b(apr_thread_t * thread,
        void *data) {
        // do func_b stuff here
}

// Cleanup before exit
void cleanup(int s) {
    printf("Caught signal %d\n", s);

    // Destroy thread pool
    apr_pool_destroy(pool);

    //apr_thread_exit(a_thread, APR_SUCCESS);
    //apr_thread_exit(b_thread, APR_SUCCESS);

    //apr_terminate();

    // Stop server and cleanup
    server->stopServer();
    delete server;

    exit(EXIT_SUCCESS);
}

int main(void) {
    // Signal handling
    signal(SIGINT, cleanup);

    // Create server
server = MyServerFactory::getServerImpl();

bool success = server->startServer();

// Initialize APR
if (apr_initialize() != APR_SUCCESS) {
    printf("Could not initialize\n");
    return EXIT_FAILURE;
}

// Create thread pool
if (apr_pool_create(&pool, NULL) != APR_SUCCESS) {
    printf("Could not allocate pool\n");
    return EXIT_FAILURE;
}

// Create a_thread thread
if (apr_thread_create(&a_thread, NULL, func_a, NULL,
        pool) != APR_SUCCESS) {
    printf("Could not create a_thread\n");
    return EXIT_FAILURE;
}

//Create b_thread thread
if (apr_thread_create(&b_thread, NULL, func_b, NULL,
        pool) != APR_SUCCESS) {
    printf("Could not create b_thread\n");
    return EXIT_FAILURE;
}

    // Join APR threads
    apr_thread_join(&status, a_thread);
    apr_thread_join(&status, b_thread);

    return EXIT_SUCCESS;
}

這或多或少按預期工作。 我唯一不確定的是清理是否正常。

  1. 清理功能似乎被多次調用(字符串“Caught signal ..”在終端上出現多次)。 有辦法防止這種情況嗎? 這有問題嗎?

  2. 我發現在使用后清理APR線程的例子不止一個。 我的方式是否足夠,還是需要一些注釋的東西? 還是我完全錯了?

APR教程線程部分中詳細解釋了APR線程清理。 按順序,清理步驟如下所示:

  1. 在線程本身中調用apr_thread_exit() 雖然Unix線程自動終止,但Windows線程卻沒有。 調用此函數以實現可移植性(如果需要,還可以返回狀態)。
  2. 在主線程中調用apr_thread_join()以等待所有線程的終止。
  3. 調用apr_pool_destroy()以釋放主內存池。 (使用apr_thread_exit()釋放子內存池。)
  4. 調用apr_terminate()以釋放其他資源(套接字等)。 請注意,在沒有這些最終步驟的情況下簡單地在另一個線程中調用exit() 會導致崩潰

他們還有一個簡短的示例程序 ,演示了一些這樣的東西。

至於你的信號處理程序發射兩次的原因,我不認為這與APR有關。 SIGINT被發送到父進程和子進程,所以我懷疑MyServer正在分支一個新進程並且都在調用處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM