简体   繁体   中英

Passing an object to a thread in C++

I have a project that creates an object of a class stored in a header file. I need this object passed into a thread from the main function.

Currently I'm using hChatThread = CreateThread(NULL,0,ChatFunc,"1",0,&dwChatThreadId); as a way of creating a thread, and it seems I cannot change the fact that the called function can only have LPVOID as a type. If I could somehow change this, I could then pass the object as an argument like so: hChatThread = CreateThread(NULL,0,ChatFunc,myObject,0,&dwChatThreadId);

But it seems this is next to impossible.

Any ideas?

Thread:

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

Main:

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

You can use LPVOID lpParameter to pass a pointer to the object, and then cast it back. Something like this:

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

The easiest way would be to make that Object a global object in the header file, and given that you included the code:

#include "headerFilesName.h"

in the file where your main function is. Then I would declare another object inside the file with the main function and just pass it its value

headerFileName myNewObject;

with this object of the class of the header file, you should be able to access the other object you created initially.

There is only one flexible solution - dynamically allocate 'w' with operator new, pass the pointer into CreateThread, cast it back in the thread function and, when/if the thread function exits/returns and the object instance is no longer required, delete it.

All the other solutions either don't work reliably, have messy globals or are inflexible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM