在c++中向线程传递对象

Passing an object to a thread in C++

本文关键字:对象 线程 c++      更新时间:2023-10-16

我有一个项目,它创建一个存储在头文件中的类的对象。我需要把这个对象从主函数传递给线程。

目前我使用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传递指向对象的指针,然后将其强制转换回来。像这样:

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;
}

最简单的方法是在头文件中使该Object成为全局对象,并且假定您包含了以下代码:

#include "headerFilesName.h"
main函数所在文件中的

。然后用main函数在文件中声明另一个对象并将其值

传递给它
headerFileName myNewObject;
使用头文件类的这个对象,您应该能够访问最初创建的其他对象。

只有一个灵活的解决方案-动态分配'w'与operator new,传递指针到CreateThread,将其转换回线程函数,当/如果线程函数退出/返回,对象实例不再需要,删除它。

所有其他的解决方案要么工作不可靠,有混乱的全局或不灵活。