簡體   English   中英

在運行循環之外聲明,分配和取消分配線程局部指針變量

[英]Declare, allocate and deallocate thread-local pointer variables outside the run loop

我有一個線程化的管道和過濾器實現,我想在其中一個過濾器中使用線程本地副本。 我自己沒有實現運行循環。 相反,基本Filter類在獲取要處理的數據時會在每個過濾器上調用process()方法。

在這種情況下,使用thread_locals存在兩個問題:1)我無法在process()方法中聲明thread_locals,因為要點是在調用process()方法時重用線程本地。

下面的示例代碼:

void process(SomeInput in) {
    thread_local SomeClass* someClass = nullptr;
    if (someClass == nullptr) someClass = new SomeClass(params);

    // do stuff here...
}

因此,在上面我初始化了SomeClass的thread_local實例。 但是我不會取消分配它,因為只要有新數據到達,process()就會被同一線程的運行循環調用。 顯然,該類永遠不會被釋放。 壞。

2)我在過濾器實現中添加了threadCleanup()方法,該方法在過濾器停止運行(並且其線程停止)時立即被調用。 雖然那將需要聲明thread_local成員變量,例如:

class SomeFilter : public Filter <...> {
// ...
private:
    thread_local SomeClass* _someClass;
}

但這不適用於類並引發:“ thread_local僅在變量聲明中被允許”

在這種情況下,聲明,分配和取消分配線程局部的正確方法是什么?

修復原始問題,而不是為自己創建的新問題:

只需使原始代碼使用std::unique_ptr 您甚至可以將其單行執行, 因為thread_local暗含static ,因此它只需初始化一次,而無需對nullptr進行每次調用測試:

void process(SomeInput in) {
    thread_local std::unique_ptr<SomeClass> someClass(new SomeClass(params));

    // do stuff here...
}

給定線程第一次調用process ,將為該線程初始化unique_ptr 當該線程退出時,銷毀unique_ptr並收集該線程的SomeClass實例, 因為在線程exit上調用thread_local析構函數

請注意,如果someClass很小,則可以將其直接存儲在thread_local存儲中,而不必在thread_local存儲指向堆的unique_ptr ,這將使您完全避免unique_ptr ,因為如前所述, thread_local表示static並在線程退出時調用析構函數:

void process(SomeInput in) {
    thread_local SomeClass someClass(params);

    // do stuff here,
    // using someClass. instead of someClass-> for member/method access,
    // and &someClass where you used to use someClass if something needs a raw
    // pointer (the raw pointer is definitely sticking around until thread
    // exit after all)
}

使用unique_ptr方法可能仍然是有利的(線程本地存儲可能受到限制/速度很慢,因此將其余的類存儲在普通堆內存中可能是值得的)。

您要查找的語法是成員變量上的static thread_local

class SomeFilter : public Filter <...> {
// ...
private:
    static thread_local SomeClass* _someClass;
}

與其執行手動清理,不如將_someClass封裝在unique_ptr ,因為線程本地在線程退出時被銷毀了:

    static thread_local std::unique_ptr<SomeClass> _someClass;

暫無
暫無

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

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