UI and Worker thread synchronization when accessing List item - c++

I have a List which has data to process. And I have 2 threads,
UI Thread : Updates/Adds the List item,
Thread 1 : Once item added into list it sends the item one by one to another thread 2,
Thread 2 : Does it's work and updates the item accordingly and Once it completes it's work, it checks list and if the corresponding item still exists in the list, If it exists it process the data.
From UI thread when closing the window, I am removing the items from map which are added from the UI. So that the thread 2 won't proceed the items which are removed from list.
And from the UI destruct or, I am deleting the item instances which are added in list.
The issue is, Thread 2 is already processing an item, In the mean time Window is closed and also the destructor deleted the item which is in processing by thread 2.
So the processing of the data by the thread 2 crashes.
I have done this in MFC. How to synchronize these 2 threads (UI deletion and Thread 2). I know there are different Thread synchronization methods in MFC. Which method is best for this scenario?

When you want to halt the operation (perhaps when the user clicks the Close button), first you tell the thread to exit. That can be done with a bool or a event (SetEvent) that the thread checks regularly. After you tell the thread to exit you must not delete the UI or any data being used by thread until you are sure the thread has exited. Use the thread handle in WaitForSingleObject to wait for the thread to exit. WaitForSingleObject suspends the calling thread until the thread handle signals that the thread has exited. Then you can continue the delete and UI shutdown.

Related

Launching thread that start as soon as semaphore is released

I'm trying to use threading and semaphore to fix a performance problem in my application.
Problem 1:
The user click on some checkbox. Each time a checkbox is clicked, a somewhat intensive saving is done in the database. The users complaint that is was slow. So now, when they click on the checkbox, I just launch a thread that do the saving (without waiting for the thread to finish). That was ok for a short while.
Problem 2:
When the user is fast and unlucky, sometimes the saving in the database crash because at the same time, the other thread is trying to save in the exact same table. So I think that what we need here is semaphore, but I'm not sure.
What I want is this to happen:
User click on checkbox 1
Launch thread 1
User click on checkbox 2
Launch thread 2 (wait for thread 1 to finish)
thread 1 finish
thread 2 finish
Here is my code:
The function we call to launch the thread
bool SampleSO::ExecuteThreadSauvegarde()
{
//Créer le thread
CWinThread* pThreadSauvegarde = AfxBeginThread(ExecuteThreadSauvegarde, this, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
if(pThreadSauvegarde)
{
pThreadSauvegarde->m_bAutoDelete = TRUE;
pThreadSauvegarde->ResumeThread();
}
return true;
}
Then the function who is called by the previous function (static)
UINT SampleSO::ExecuteThreadSauvegarde(LPVOID pParam)
{
SampleSO* pSampleSO = (SampleSO*)pParam;
LONG dwSemCount;
HANDLE hSemaphore = OpenSemaphore( SYNCHRONIZE |SEMAPHORE_MODIFY_STATE, FALSE, _T("Sauvegarde") );
//this is the function that call the saving
pSampleSO->Sauvegarde();
ReleaseSemaphore(hSemaphore, 1, &dwSemCount);
return 1;
}
How can I modify my code so that the critical section is only accessed one thread at the time and that the thread that are waiting for the semaphore go in the critical section as soon as it's released (one at the time).
Thanks!
What you need is not so many threads. Instead, spawn a single worker thread to deal with DB operations. When the user clicks, simply post a message/command via a queue to the worker thread. The worker simply waits for a command, executes it, and goes back to blocking-waiting on the queue. This will require no synchronization beyond thread-safety for the queue itself, which will be trivial because it's single-producer, single-consumer.

Main thread closed while the worker thread not finished

In the MFC Project ,I have main thread focusing on the dialog. another worker thread focusing on receiving data from server ,parsing the data and updating the data into database.
the data from server is quite huge. so I destroy the dialog by clicking the close button while the worker thread is not finished. But the worker thread is not independent. while I delete the object create in the main thread, the worker thread can't continue , that is to say. some error like the access violation problem. (because the worker thread use the member variables in the xxxxdialog class).
the way I create a thread is AfxBeginThread, i use the method waitforsingleobject, still can not work...
I don't want to force to kill the worker thread, otherwise, it will cause memory leak...
You should terminate the workthread safely before the maindlg is destroyed.
Here is the answer [Terminating a thread gracefully not using TerminateThread() ]

Application crashes on dialogue close with threads running

In my application I have a modal dialog which contains about 20 different combo boxes which are bind to certain fields in the databases. The database is huge and on the loading of dialog I have to load all the combo boxes from the databases. So I setup 20 threads (1 each for every combo box).
Everything works fine, but the problem only occurs when the user closes the dialog with close or cancel button or OK button while the threads are running; in that case the application crashes.
I have tried to terminate the threads prematurely as well but that does not help. Here is the thread termination code
if(m_iNoOfThreadsCompleted != m_iTotalThreads)
{
for(int i = 0; i < m_iTotalThreads - 1; i++)
{
if (m_threads[i] != NULL)
{
GetExitCodeThread(m_threads[i]->m_hThread, &exit_code);
if(exit_code == STILL_ACTIVE)
CloseHandle(m_threads[i]->m_hThread);
}
if(m_iNoOfThreadsCompleted == m_iTotalThreads)
break;
}
}
What is the issue? Or do I need to use a better approach?
Synchronizing threads is generally done using events.
// Before Creating threads
HANDLE hEndEvent = CreateEvent(NULL,FALSE,FALSE,NULL);
// Pass handle to threads
Then on termination
SetEvent(hEndEvent);
WaitForMultipleObjects(m_iTotalThreads,m_threads,TRUE,INFINITE); // Wait for all threads to end
// Loop through and close all the thread handles
Note that you need to be occasionally looking for the end event to be set otherwise your threads won't end.
// In Thread
if (WaitForSingleObject(hEndEvent,0)==WAIT_OBJECT_0) {
// Clean up
return 0;
}
CloseHandle does not terminate the thread. You can call TerminateThread but it's not the nicest thing to do...
What is normal is to provide your threads with a manual-reset event object that signals a shutdown is taking place. Sometimes it's also good to have a flag so that threads can abort lenghty operations. The threads carry on their work as usual, and whenever they have to wait on some object, you include the shutdown event object in that wait.
So the procedure on exit is normally to do this:
Set the shutdown flag
Signal the shutdown event
Resume all threads (in case any are suspended)
WaitForMultipleObjects on all thread handles, with an appropriate timeout
Call TerminateThread on any threads that did not exit within the timeout
Close all thread handles
Destroy the shutdown event
This approach requires that threads are created with _beginthreadex, so that you are responsible for closing the handles. The benefit of this is that you can wait on threads, even after they've exited (of course an exited thread is already in the signaled state).
As an alternative to what paddy describes another approach would be to instead of having 20 threads that load the comboboxes to just have one thread that loads. By having 20 threads you may not be speeding up things anyway depending on your database library.
Then when that thread is loading periodically (like between each checkbox) check whether user pressed cancel or not, if so then stop processing and exit the thread.
This would make the handling less complicated than managing 20 threads IMHO.

How can i create several thread in a queue with Qt?

How can I create threads in a queue with Qt that execute step by step (when one thread completed another thread started)?
Please give me a code example?
Look at QThreadPool.
However, as Frank pointed out, if you execute things after each other, there is no need for threads.
There is a "finished()" signal from the QThread object. In your thread manager thread (i.e. your main qwidget or qmainwindow), you could have a queue manager class that has a slot to which this signal is connected. The slot would initialize and execute the next thread in the queue when it receives the finished signal from the currently running thread.
This would prevent blocking in your manager thread and allow you to execute these thread objects from a queue as you describe.
Make sure that each time you respond to a finished signal, you connect the next thread's finished signal to your queue manager slot. You also want to make sure that you start the thread in your "add to queue" method if there are no other threads currently running.

Qt signals reach UI thread with noticeable delay

I have a worker thread in my application, which occasionally recieves information that should be quickly displayed in QML UI. When I have such portion of information, I emit signal, which is received by object that lives on UI thread.
I want this process to be very responsive, so that changes are displayed in QML UI as quickly as possible (this matters because worker thread handles external controller, and I want the shortest "critical path" between user interaction with controller and UI change).
However I discovered, that the time difference between emit signal() and slot called in UI thread is always 20-40 milliseconds. Why so?
What can I do to speed up this? I tried calling QCoreApplication::processEvents() in worker thread after signal is emitted, but this barely changes anything.
Some thoughts:
Can I call processEvents but for UI thread somehow?
Use event with high priority instead of signal. Will it help?
OS: Win8.1, Qt 5.5
When you emit a signal from a worker thread to the UI thread, it is put into the UI event queue, and delivered when the event queue is pumped and reaches that message. If your worker thread is a higher priority than your UI thread, then the UI thread will have to wait until the worker thread blocks. If the worker thread is the same priority it will complete it's time quanta, which may be 20ms. You can make your signal connect Direct rather than Queued, and then you will need to take care of thread safety yourself.