hypheni
hypheni

Reputation: 816

c++ multi thread object out of scope

I'm starting a worker thread (written inside a new class) from a UI event (seperate class). Now as the new worker thread is created from main UI thread, it is immediately returning from the control, which causing the worker thread class object to be destroyed. Better explanation can be found by checking below code.

//class - UI  
void CUIClass::button_click()
{
  CDataProcess obj;
  obj.Start();
}

//class - DataProcess
CDataProcess::CDataProcess()
{
}

CDataProcess::~CDataProcess()
{
}

void CDataProcess::Start()
{
  CWinThread *pThread = AfxBeginThread(DataProcessingThread, this);
}

UINT CDataProcess::DataProcessingThread()
{
  //some processing
}

Now some of the possible solutions I thought about are:

What else could be the proper solution?

Upvotes: 1

Views: 1265

Answers (3)

hypheni
hypheni

Reputation: 816

Well, I think I have created some serious trouble for me. I should stick to DataProcess functionality inside a seperate class which can be called from a thread started by UI class. That way it solves every single issues.

Upvotes: 0

rezdm
rezdm

Reputation: 165

It depends on what you're trying to achieve. Obviousely, you need to create a worker object that lives longer than button_click callback:

CDataProcess* obj = new CDataProcess();
obj->Start();

Assuming by name AfxBeginThread, you're in Windows (more specific, MFC) environment. You can use any of "task pooling" techniques (once again, depends on what you're trying to achieve). Connection points, thread pools -- you name it. How you need to detect when a task is finished? How to show it to a user? Will you allow a user to cancel a task? etc, etc.

Upvotes: -1

David Haim
David Haim

Reputation: 26536

Well , if you are going to open a thread for each click on the button (which I think you need to reconsider) , a Thread pool is most suitable here.

basically , you want to write your onClick logic in one function (that may call other functions and objects , surely) which will be the callback function for the onClick event. then you ask your thread pool to execute the callback asynchrounosly.

you may also want to read about std::async which launches functions asynchrounosly , but keep in mind that if your thread is heavy , you might want to go with a thread pool anyway.

Upvotes: 2

Related Questions