簡體   English   中英

Apache模塊中的靜態變量是否要初始化一次?

[英]Static Variables in Apache module are initialized more then once?

我為Apache HTTP服務器編寫了一個模塊,發現了奇怪的行為。 我假設靜態變量僅初始化一次,但是我在下面編寫了代碼,並向Apache發出了兩個請求,輸出為:


test_handler: isInit=0
test_handler: isInit=1

test_handlere: isInit=0
test_handlere: isInit=1

測試代碼:


static int isInit = 0;

static int test_handler( request_rec *r ) {
    fprintf(stderr,"\n\natest_handler: isInit=%d", isInit );
    if( !isInit ) {
        isInit = 1;
    }
    fprintf(stderr,"\natest_handler: isInit=%d", isInit );
    fflush(stderr);
    return DECLINED;
}

static void register_hooks(apr_pool_t *p) {
    fprintf(stdout,"register_hooks\n"); 
    ap_hook_translate_name(test_handler, NULL, NULL, APR_HOOK_FIRST);    
    fprintf(stdout,"register_hooks done\n");
}

module AP_MODULE_DECLARE_DATA test_module = {
    STANDARD20_MODULE_STUFF, 
    NULL,                  /* create per-dir    config structures */
    NULL,                  /* merge  per-dir    config structures */
    NULL,                  /* create per-server config structures */
    NULL,                  /* merge  per-server config structures */
    NULL,                  /* table of config file commands       */
    register_hooks  /* register hooks                      */
};

這個問題與線程有關,因為當我向Apache發出10個請求時,我看到isInit=1, isInit=1在某些情況下為isInit=1, isInit=1在其他情況下為isInit=0, isInit=1

我的問題是, 如何定義一個變量,該變量將在test_handler()訪問,並在調用函數之間保留其值?

我認為,我發現了問題。 適用於Linux的Apache服務器創建了多個“子”服務器來服務並行請求。 每個虛擬服務器都會加載配置,包括模塊實例,因此,如果ApacheServer創建8個子服務器進程,則需要8個isInit變量副本。 您可以將Apache配置為僅創建一台服務器(不推薦-性能)。 另一種方法是將Apache Server配置為使用其他Multi-Proccess技術,我讀過abot prefork和worker。 根據Windows上的Apache2文檔,服務器使用Windows API,因此您可以遷移到Windows或編寫可用作多個並行實例的模塊。

我認為這可能與多個線程同時運行時發生的競爭狀況有關。 關鍵字static是僅限制變量的范圍,因此它不是解決方案-出於競爭條件排除的目的,請使用mutexes之類的東西。 說到在連接內的函數調用之間保留一些變量,您需要將此變量存儲在與連接相關的結構中(例如,請參見request_rec->notesrequest_rec->connection->notes )。

暫無
暫無

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

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