簡體   English   中英

將shared_ptr或unique_ptr傳遞給_beginthreadex

[英]Passing a shared_ptr or unique_ptr to _beginthreadex

我想知道這是可能的。 創建一個TestClass類型的shared_ptr或unique_ptr。

然后調用_beginthreadex並將其靜態傳遞給該類作為要執行的函數,並將之前創建的shared_ptr或unique_ptr用作數據。 像這樣:

shared_ptr<TestClass> p = make_shared<TestClass>(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);

我通常在沒有智能指針的情況下使用此方法,通常會創建TestClass的普通指針,並將TestClass的靜態方法和指針本身作為數據傳遞,然后在靜態方法內部將其強制轉換為(TestClass *)並運行成員方法類等,做的工作,當線程完成時,我刪除指針。 像這樣:

    TestClass * p = new TestClass(count, "test");
    HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart,p, 0, NULL);

我要實現的是使智能指針在線程結束時自動刪除對象,因為智能指針將超出范圍。

當我按照上面描述的方式進行操作時,編譯器將顯示此錯誤:

“不存在從“ std :: shared_ptr”到“ void *”的合適轉換函數”

_beginthreadex看起來像c函數,要實現所需的功能,您需要調用復制構造函數 (或在unique_ptr情況下移動 )以轉移所有權,這在c中是不可能的。

您可以考慮使用std::thread類,該類可與其他std套件一起使用。

假設您要運行:

void ThreadStart(std::shared_ptr<TestClass> p);

你可以用

void ThreadStart(std::shared_ptr<TestClass> p)
{
    cout << p->count << " " << p->name << endl;
}

int main()
{
    shared_ptr<TestClass> p = make_shared<TestClass>(33, "test");
    std::thread thr(ThreadStart, p);
    thr.join();
}

如果使用std::unique_ptr ,則需要將其std::move線程函數,因此實際上它將在線程末尾刪除:

void ThreadStart(std::unique_ptr<TestClass> p);
...
unique_ptr<TestClass> p = make_unique<TestClass>(33, "test");
std::thread thr(ThreadStart, std::move(p));

使用shared_ptr::getunique_ptr::get可以訪問指向托管對象的指針。

shared_ptr<TestClass> p = make_shared<TestClass>(count, "test");
HANDLE hth1 = (HANDLE)_beginthreadex(NULL, 0, p->ThreadStart, p.get(), 0, NULL);

暫無
暫無

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

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