簡體   English   中英

需要停止線程並從線程例程本身加入

[英]Need to stop a thread and join from the thread routine itself

我在 C++ 中研究 state 設計模式,我有多個狀態。 一些州的線程例程受pthread_create限制。 現在有些情況下,一個 state 過渡到另一個 state,因此需要停止線程並且需要通過pthread_join清理 memory。

所以總而言之,我需要從線程例程本身停止線程。 我怎樣才能做到這一點?

或者有沒有辦法在線程例程完成時自動進行 memory 清理?

PS:問題是,當我從線程例程當前 state 析構函數進行 state 轉換到另一個 state 時。 在當前 state 的析構函數內部,我需要停止並加入線程。 否則會發生 memory 泄漏。

所以總而言之,我需要從線程例程本身停止線程。 我怎樣才能做到這一點?

從線程底部正在執行的 function 返回。

memory 需要清洗

您可以在線程終止后通過從另一個線程加入來清理線程。 您可以通過在終止線程之前分離線程來避免這樣做。


PS 更喜歡使用可移植的std::thread (或std::jthread )而不是系統特定的線程 API。


您可以添加共享代碼如何使用 std::thread 從例程本身終止線程嗎

例子:

auto thread_fun = [] {
    return; // this terminates the thread
};
std::thread t(thread_fun);
t.join(); // this waits for the thread to end, and cleans it up

暫無
暫無

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

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