[SOLVED] Multithreading with CreateThread
-
this is my first approach:
@
class testA
{
public:
testA() {}
QString strDataMember;
void myFunc()
{
// below line gets executed
qDebug() << "Thread is running";
// i get segfualt because "this" is null and not initilized!!!
this->strDataMember = "Hello world!";
}
};int main(int argc, char *argv[])
{
DWORD dwThreadId;
if (CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&testA::myFunc, NULL, 0, &dwThreadId) == NULL)
{
qDebug() << "Error while creating thread.";
return 1;
}
else
{
// below line is executed, so thread is successfully created!
qDebug() << "Thread is created.";
}
@since "this" is not initialized i came to an idea of putting class "testA" inside a static library(*.a) .
so in my second approach i have 2 projects, one for my app and one for the lib.
@
in my lib i have below code:
testA::testA()
{
}void testA::getMessage(QString &strMessage)
{
strMessage = "Hello world!";
}in my application main function i have below code
int main(int argc, char *argv[])
{
testA obj;
QString strTest;
// after below line i get "Hello world!" inside strTest(just to make u sure i have access to the lib)
obj.getMessage(strTest);
// i clear it
strTest.clear();// now calling the lib function inside a thread
DWORD dwThreadId;
if(CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &testA::getMessage, &strTest, 0, &dw1) == NULL)
{
qDebug() << "failed to create thread.";
}
// after above code i expect strTest to contain "Hello World!" string but it is empty.
if(strtest.isEmpty())
{
qDebug() << "Thread function parameter failed.";
}
// after above code i get segFault
}
@
so to wrap it up, i have 2 approaches for running a function inside another thread using CreateThread.
in my first approach the problem is that class obj is not initialized yet.
and in my 2nd approach the thread parameter is not assigned a value and i don't know why!any suggestions?
-
i had forgetten to wait for the thread how thick i could be :-D
but im happy i could figure it out my self:-)below code solved the probelm for 2nd approach:
@
HANDLE hdl;
hdl = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE) &testA::getMessage, &strTest, 0, &dw1);
if(hdl == NULL)
{
qDebug() << "failed to create thread.";
}
WaitForSingleObject(hdl,INFINITE);
if(strTest.isEmpty())
{
qDebug() << "Parameter failed.";
}@