How to wake up a sleeping thread in mac - multithreading

I am new to Objective C. I am putting a thread to sleep using
[NSThread sleepForTimeInterval:10.0f];
but when particular events occurs I want to wake up this sleeping thread. How do I wake up this sleeping thread?
Thanks

This can't be done. If a thread sleeps using that method it cannot be woken until the time is over.
Something like this could be emulated using a NSCondition object.

I would propose the use of NSTimer over the use of NSThread, mainly due to the limitations of execution control of a sleeping thread. NSTimer allows immediate cancellation, via a call to invalidate, which could be called in response to some user cancellation. NSTimer provides two types of firing: repeating and non-repeating. The code below uses an NSTimer to make repeated calls to a specified selector:
//delayInSeconds and intervalInSeconds are NSTimeInterval values calclulated elsewhere
NSDate *fireDate = [[NSDate date] dateByAddingTimeInterval:delayInSeconds];
//Create a timer that will repeat, starting with the fireDate
//Optionally, userInfo could contain an object. checkSomething:
// would take one parameter, the NSTimer which would carry the userInfo
//timer is a strong property defined for a particular class, as an instance variable.
self.timer = [[NSTimer alloc] initWithFireDate:fireDate
interval:intervalInSeconds
target:self
selector:#selector(checkSomething:)
userInfo:nil
repeats:TRUE];
//Launch the timer on the main run loop
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
Limitations of Sleeping an NSThread
One clear disadvantage of sleeping a thread is that waking it up is such an unconventional solution (involving the use of a signal to kill the process), that one of the only options left is to use a flag. This is a problem because there will be a delay for significant sleep times. For instance, if a sleep time is 10 seconds, then there could be as much as a 10 second delay before the flag is read, and the application responds.
Since sleepForTimeInterval is a class method, it is not possible to call cancel on the sleeping thread.

Related

How to ensure thread is not terminated before finalizer completes

I have an unmanaged class that is running a message loop for a child Win32 window. When the program goes to close, it starts the finalizer for the managed class that holds the unmanaged reference to this class. Because another thread is dependent on this class, I need the finalizer to wait until the message loop thread has completed a loop and exits and terminates. However, the timeout loop I have apparently takes too long for the GC finalizer thread or the main thread terminates destroying the entire process.
Is there a way to tell the GC to not timeout a thread for finalizers? I.E. - I need the finalizer thread to block for a little while in the finalizer so it can complete terminating the message loop thread and then release the unmanaged resource.
Here is my finalizer so you get an idea of what's going on:
PONms::NestedWin32::
!NestedWin32()
{
if (msgLoop->IsAlive)
{
winProcess->EndThread(); // blocks and waits for message loop thread to terminate
// and GC apparently doesn't like this causeing the
// entire process to terminate here.
}
if (childHandle != nullptr)
{
DestroyWindowCore(childHandle);
}
if (winProcess != nullptr)
{
delete winProcess; // memory leak due to resource not being released
}
}
I'm thinking I went about this the wrong way, just expecting the code to behave properly and the finalizer to complete.
Here is the simple method I use to poll the other thread to see if it has terminated:
void PONms::NestedWin32UM::
EndThread()
{
int timeOut = 5000;
threadContinue = false;
SendNotifyMessage(childWin, WM_CLOSE, 0, 0);
while (threadActive && timeOut > 0)
{
POCPP::Threading::SleepThreadOne();
timeOut--;
}
}
int timeOut = 5000;
That is a pretty drastic mismatch with the default CLR policy for the finalizer thread timeout. You've got 2 seconds to get the job done. Roughly 10 billion instructions on a modern processor. We can't see what SleepThreadOne() does, but Sleep(1) doesn't sleep for 1 millisecond. Default sleep granularity is 15.625 msec so you'll end up waiting for as long as 78 seconds.
Technically you can extend the timeout by custom-hosting the CLR, ICLRPolicyManager::SetTimeout() method, OPR_FinalizerRun setting. But, realistically, if you can't hack it with 10 billion instructions then extending it isn't very likely to bring relief.
Debugging this isn't that simple, those 2 seconds are over in a hurry. Look at structural fixes. Don't use a bool to synchronize code, use an event (CreateEvent winapi function). And WaitForSingleObject() with a timeout to wait for it to be set. Use 1000 msec max so you give the finalizer thread enough breathing room. And don't be too nice asking the message loop to quit, WM_CLOSE is far too friendly. Code is apt to respond to it with a "Save changes?" message box, that's a guaranteed fail. Use PostQuitMessage(). Or don't bother at all, programs should terminate through the UI and you seem to need to pull the rug another way.

Disabling a System.Threading.Timer instance while its callback is in progress

I am using two instances of System.Threading.Timer to fire off 2 tasks that are repeated periodically.
My question is: If the timer is disabled but at that point of time this timer is executing its callback on a thread, then will the Main method exit, or will it wait for the executing callbacks to complete?
In the code below, Method1RunCount is synchronized for read and write using lock statement ( this part of code is not shown below). The call back for timer1 increments Method1RunCount by 1 at end of each run.
static void Main(string[] args)
{
TimerCallback callback1 = Method1;
System.Threading.Timer timer1 = new System.Threading.Timer(callback1,null,0, 90000);
TimerCallback callback2 = Method2;
System.Threading.Timer timer2 = new System.Threading.Timer(callback2, null, 0, 60000);
while (true)
{
System.Threading.Thread.Sleep(250);
if (Method1RunCount == 4)
{
//DISABLE the TIMERS
timer1.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
timer2.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
break;
}
}
}
This kind of code tends to work by accident, the period of the timer is large enough to avoid the threading race on the Method1RunCount variable. Make the period smaller and there's a real danger that the main thread won't see the value "4" at all. Odds go down considerably when the processor is heavily loaded and the main thread doesn't get scheduled for while. The timer's callback can then execute more than once while the main thread is waiting for the processor. Completing missing the value getting incremented to 4. Note how the lock statement does not in fact prevent this, it isn't locked by the main thread since it is probably sleeping.
There's also no reasonable guess you can make at how often Method2 runs. Not just because it has a completely different timer period but fundamentally because it isn't synchronized to either the Method1 or the Main method execution at all.
You'd normally increment Method1RunCount at the end of Method1. That doesn't otherwise guarantee that Method1 won't be aborted. It runs on a threadpool thread, they have the Thread.IsBackground property always set to true. So the CLR will readily abort them when the main thread exits. This again tends to not cause a problem by accident.
If it is absolutely essential that Method1 executes exactly 4 times then the simple way to ensure that is to let Method1 do the counting. Calling Timer.Change() inside the method is fine. Use a class like AutoResetEvent to let the main thread know about it. Which now no longer needs the Sleep anymore. You still need a lock to ensure that Method1 cannot be re-entered while it is executing. A good way to know that you are getting thread synchronization wrong is when you see yourself using Thread.Sleep().
From the docs on System.Threading.Timer (http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx):
When a timer is no longer needed, use the Dispose method to free the
resources held by the timer. Note that callbacks can occur after the
Dispose() method overload has been called, because the timer queues
callbacks for execution by thread pool threads. You can use the
Dispose(WaitHandle) method overload to wait until all callbacks have
completed.

Suspend main thread in qt

I want to make a function that stops the main thread and restarts restarts it after a couple of seconds. I tried the following:
void Mainwindow::timeout()
{
QTimer timer;
timer.setSingleShot(true);
timer.setInterval(time*1000);
connect(&timer,SIGNAL(timeout()),MainWindow::thread(),SLOT(start()));
timer.start();
SuspendThread(MainWindow::thread());
}
Unfortunately this doesnt do a whole lot... Any tips?
Maybe I am overlooking something, but a "function that stops [...] and restarts after a couple of seconds" sounds like sleep() to me. Let the OS do the timing instead of re-inventing the wheel.
Or is there any reason you can't post some message to the main thread? In this simple use case maybe even via a single mutex would be enough. Set the mutex from another thread, check it in the main threads event loop and possibly call sleep() directly.
That also eases debugging, as you have a single place the main thread will go sleeping willingly instead of being suspendend on the fly by other threads.
your timer object is destroyed at the end of the the Mainwindow::timeout() function, so it will never emit its timeout() signal.
I am not sure why you would want to stop event loop, but you can sleep your thread by waiting on locked mutex for x milliseconds.
In the code below you will use waitCondition.wait(&mutex, msecs); to wait on a condition variable for maximum msecs milliseconds. Since mutex is locked, as there is no another thread which will send wake up signal, this will block your thread for timeout milliseconds. Reference is here.
#include <QWaitCondition>
#include <QMutex>
class Sleep
{
public:
static void msleep(unsigned long msecs)
{
QMutex mutex;
mutex.lock();
QWaitCondition waitCondition;
waitCondition.wait(&mutex, msecs);
mutex.unlock(); // Not necessary since new mutex will always be created,
// but since destroying locked mutex
// is bringing undefined behavior, let's follow some ethics
}
};

Starting a sleeping thread in .NET

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.

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.

Resources