簡體   English   中英

將對象傳遞給C ++中的線程

[英]Passing an object to a thread in C++

我有一個項目,該項目創建存儲在頭文件中的類的對象。 我需要將此對象從主函數傳遞到線程中。

目前,我正在使用hChatThread = CreateThread(NULL,0,ChatFunc,"1",0,&dwChatThreadId); 作為創建線程的一種方式,看來我無法改變被調用函數只能將LPVOID作為類型的事實。 如果我可以以某種方式更改它,則可以像這樣將對象作為參數傳遞: hChatThread = CreateThread(NULL,0,ChatFunc,myObject,0,&dwChatThreadId);

但這似乎幾乎是不可能的。

有任何想法嗎?

線:

DWORD WINAPI ChatFunc(LPVOID randparam)
{
    ServerMain(myObject); //need to pass object again here to be used in other functions
    return 0;
}

主要:

int main(int argc, char *argv[])
{
    myObject w;
    w.exec();
    hChatThread = CreateThread(NULL,0,ChatFunc,"1",0,&dwChatThreadId);
    return 0;
}

您可以使用LPVOID lpParameter將指針傳遞給對象,然后將其LPVOID lpParameter回退。 像這樣:

int main(int argc, char *argv[])
{
    myObject w;
    w.exec();
    hChatThread = CreateThread(NULL,0,ChatFunc,&w,0,&dwChatThreadId);

    // wait for the thread to terminate,
    // otherwise w might get destroyed while the thread
    // is still using it (see comments from @MartinJames)

    return 0;
}

DWORD WINAPI ChatFunc(LPVOID param)
{
     myObject* p = static_cast<myObject*>(param);
    ServerMain(p); //need to pass object again here to be used in other functions
    return 0;
}

最簡單的方法是使該對象成為頭文件中的全局對象,並假定您包含以下代碼:

#include "headerFilesName.h"

在您主要功能所在的文件中。 然后我將使用main函數在文件中聲明另一個對象,然后將其值傳遞給它

headerFileName myNewObject;

使用頭文件類的該對象,您應該能夠訪問最初創建的另一個對象。

只有一種靈活的解決方案-使用new運算符動態分配'w',將指針傳遞給CreateThread,將其強制轉換回線程函數中,並且,當/如果線程函數退出/返回且不再需要對象實例,則刪除它。

所有其他解決方案要么運行不可靠,要么全局混亂,要么不靈活。

暫無
暫無

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

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