Starting a sleeping thread in .NET - multithreading

if a threadA is sleeping, how will another thread threadB call threadA to start ?
Please provide an example if possible.

Instead of sleeping you will want to create an EventWaitHandle and use WaitOne with a timeout.
When you want the thread to wake-up early, you will simply set the event to signaled.
First create the EventWaitHandle:
wakeUpEvent = new EventWaitHandle(false, EventResetMode.ManualReset);
Then in your thread:
wakeUpEvent.WaitOne(new TimeSpan(1, 0, 0));
When the main program wants to wake up the thread early:
wakeUpEvent.Set();
Note: You can either set the event to auto reset or manual reset. Auto reset means once WaitOne returns from the event, it will set it back to non signaled. This is useful if you are in a loop and you signal multiple times.

A thread can be started by waiting on a WaitObject and having the other thread calling the Set method on it. Look at the WaitHandle.WaitOne method.
Here's article that may be of help as well.

Related

How to know when CloseThreadPool() function completes?

i am new to Sockets programming and going through the Documentation.
From a documentation i found about CloseThreadPool() function :
CloseThreadpool function. The thread pool is closed immediately if there are no outstanding callback objects that are bound to the thread pool. If there are, then the thread pool is released asynchronously when those outstanding objects are freed.
This thread pool is in a thread itself. my main thread takes input for exit. if exit is inputted i set global variable KEEP_LISTENEING to false.
How would i wait my main thread to stop/sleep untill this function truly completes in another thread ?
Use a cleanup group to wait for all callbacks. The sequence is:
CreateThreadpoolCleanupGroup()
SetThreadpoolCallbackCleanupGroup(&CallbackEnvironment, pointerCleanup, ...)
CloseThreadpoolCleanupGroupMembers(, FALSE, )
CloseThreadpoolCleanupGroup()

For a Multithreading program, if one thread dies how you can know that ?

For a Multithreading program, if one thread dies how you can know that ?
My idea:
(1) use ps to check LWP but it is manually, not efficient.
(2) set a try-catch in each thread, if it exit non-normally, catch it.
(3) let the dying-thread send a message to std::cout or main thread.
Other better ideas ?
thanks
You could use pthread_cleanup_push(3) at a very early stage in the thread function. The function given to pthread_cleanup_push could set some flag which a "watcher" thread can pick up. pthread_cleanup_push is also honoured by pthread_exit and is not bound to exceptions.
Edit: A second way to do this: Use pthread_key_create(3) with a destructor function and call pthread_setspecific(3) early in the thread function. The destructor function can signal the watching thread it's imminent death.
You could simply use pthread_cleanup_push and pthread_cleanup_pop to execute a cleanup handler on thread exit. This would catch cancellation/pthread_exit events.

Thread scheduling issue with MFC and AfxBeginThread

I'm creating a worker thread in MFC with AfxBeginThread, but the thread is not getting scheduled. Here's the code:
CWinThread* worker = AfxBeginThread(initialUpdateWorkerThread, this);
DWORD dwExitCode = 0;
while(GetExitCodeThread(worker->m_hThread, &dwExitCode))
{
if(dwExitCode != STILL_ACTIVE)
break;
::Sleep(100);
}
When I run this, this loop just livelocks because initialUpdateWorkerThread is never called (I've put break points and message boxes at the top of it) so dwExitCode is always STILL_ACITVE. But if I put in a call to AfxMessageBox before the loop but after AfxBeginThread then the function is called. This makes me think that somehow I'm not calling the right function to get the thread scheduled, but a call to AfxMessageBox causes it to get scheduled.
How can I force the thread to be scheduled? I would think sleep would do that, but in this case it doesn't seem to.
Your worker thread is probably trying to send your main thread a message, but since you aren't processing messages on on the main thread, the worker thread simply waits. You can confirm this by simply breaking into the debugger to see what the worker thread is doing.

How to wait in the main thread until all worker threads have completed in Qt?

I have designed an application which is running 20 instance of a thread.
for(int i = 0;i<20;i++)
{
threadObj[i].start();
}
How can I wait in the main thread until those 20 threads finish?
You need to use QThread::wait().
bool QThread::wait ( unsigned long time = ULONG_MAX )
Blocks the thread until either of
these conditions is met:
The thread associated with this
QThread object has finished execution (i.e. when it returns from
run()). This function will return true if the thread has finished. It
also returns true if the thread has
not been started yet.
time milliseconds has elapsed. If time is
ULONG_MAX (the default), then the wait
till never timeout (the thread must
return from run()). This function
will return false if the wait timed
out.
This provides similar functionality to
the POSIX pthread_join() function.
Just loop over the threads and call wait() for each one.
for(int i = 0;i < 20;i++)
{
threadObj[i].wait();
}
If you want to let the main loop run while you're waiting. (E.g. to process events and avoid rendering the application unresponsible.) You can use the signals & slots of the threads. QThread's got a finished() singal which you can connect to a slot that remembers which threads have finished yet.
You can also use QWaitCondition
What Georg has said is correct. Also remember you can call signal slot from across threads. So you can have your threads emit a signal to you upon completion. SO you can keep track of no of threads that have completed their tasks/have exited. This could be useful if you don't want your Main thread to go in a blocking call wait.

parallel c++ join in .net 1.1

I'm trying to spawn and then join two threads using MS VS 6.0 (2003), MS .NET Framework 1.1.
The following seems to be a reasonable solution:
CWinThread* thread1 = AfxBeginThread(worker, &parallel_params);
CWinThread* thread2 = AfxBeginThread(worker, &parallel_params);
WaitForSingleObject(thread1->m_hThread, INFINITE);
WaitForSingleObject(thread2->m_hThread, INFINITE);
but my main concern has to do with this statement in the documentation: "If this handle is closed while the wait is still pending, the function's behavior is undefined." When do handles get closed? Does ending the worker proc close the handle? If so, am I in trouble? Is this really a reasonable solution??
In order to be able to safely wait on the thread's handle, you should:
Start the thread suspended
Set the m_bAutoDelete member to false, so that the returned CWinThread* is not deleted automatically once the thread exits
Resume the thread
And finally wait on the handle the way you do.
Alternatively, you can start the thread suspended, then duplicate the handle, leave m_bAutoDelete as is, and finally wait on the new handle. This way the CWinThread* will indeed be deleted, but you'll still have a handle to wait on. Also, don't forget to close the handle once your done waiting on it.
If you leave your code as is, you might not even get to wait on a closed handle. If the thread exits you get to the wait function, the CWinThread* pointer might point to a deleted object, and you'll get an exception.

Resources