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
}
};
Related
I have a question about condition_variable.
Having this code
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <condition_variable>
std::condition_variable cv;
std::mutex mut;
int value;
void sleep() {
std::unique_lock<std::mutex> lock(mut);
// sleep forever
cv.notify_one();
}
int main ()
{
std::thread th (sleep);
std::unique_lock<std::mutex> lck(mut);
if(cv.wait_for(lck,std::chrono::seconds(1))==std::cv_status::timeout) {
std::cout << "failed" << std::endl;
}
th.join();
return 0;
}
How to resolve this deadlock
Why the wait_for blocks even after the 1 sec.
Is the mut necessary for the thread th ?
Thanks.
Why the wait_for blocks even after the 1 sec?
How do you know that the main thread ever makes it to the cv.wait_for(...) call?
It's not 100% clear what you are asking, but if the program never prints "failed," and you are asking why not, then probably what happened is, the child thread locked the mutex first and then it "slept forever" while keeping the mutex locked. If that happened, then the main thread would never be able to get past the std::unique_lock<std::mutex> lck(mut); line.
Is the mut necessary for the thread th ?
That depends. You certainly don't need to lock a mutex in a thread that does nothing but "// sleep forever," but maybe the thread that you are asking about is not exactly the same as what you showed. Maybe you are asking how wait() and notify() are supposed to be used.
I can't give a C++-specific answer, but in most programming languages and libraries, wait() and notify() are low-level primitives that are meant to be used in a very specific way:
A "consumer" thread waits by doing something like this:
mutex.lock();
while ( ! SomeImportantCondition() ) {
cond_var.wait(mutex);
}
DoSomethingThatRequiresTheConditionToBeTrue();
mutex.unlock()
The purpose of the mutex is to protect the shared data that SomeImportantCondition() tests. No other thread should be allowed to change the value that SomeImportantCondition() returns while the mutex is locked.
Also, you may already know this, but some readers might not; The reason why mutex is given in cond_var.wait(mutex) is because the wait function temporarily unlocks the mutex while it is waiting, and then it re-locks the mutex before it returns. The unlock is necessary so that a producer thread will be allowed to make the condition become true. Re-locking is needed to guarantee that the condition still will be true when the consumer accesses the shared data.
The third thing to note is that the consumer does not wait() if the condition already is true. A common newbie mistake is to unconditionally call cv.wait() and expect that a cv.notify() call in some other thread will wake it up. But a notify() will not wake the consumer thread if it happens before the consumer starts waiting.
Writing the "producer" is easier. There's no technical reason why a "producer" can't just call cond_var.notify() without doing anything else at all. But that's not very useful. Most producers do something like this:
mutex.lock();
... Do something that makes SomeImportantCondition() return true;
cond_var.notify();
mutex.unlock();
The only really important thing is that the producer locks the mutex before it touches the shared data that are tested by SomeImportantCondition(). Some programming languages will let you move the notify() call after the unlock() call. Others won't. It doesn't really matter either way.
I am trying to pause my thread waiting for an user action. I know I could use Qt::BlockingQueuedConnection but that is not the point here. I would like to use QWaitCondition but I don't understand in this particular case why I need a QMutex.
Consider this code :
class MyWorker: public QThread
{
private:
QMutex mDummy;
QWaitCondition mStep1;
void doStuff1(){}
void doStuff2(){}
signals:
void step1Finished();
public:
MyWorker(...): {}
protected:
void run()
{
doStuff1();
emit step1Finished();
mDummy.lock();
mStep1.wait(mDummy);
mDummy.unlock();
doStuff2();
}
}
In this case the QMutex mDummy seems useless to me. I use it only because wait() need it as parameter.
I know that wait() unlock the mutex then (re)lock it after waking up, but why there no possibility to use wait() without it?
First of all, wait condition needs a mutex, so you gotta give it one. That's what a wait condition is. It is the most low level signalling mechanism between threads in multi-threading, so it doesn't provide the "convenience" you seem to be looking for.
But you also need the mutex to get things work right. A wait condition might have a spurious wakeup, that is it could be woken up for "no reason" (google "wait condition spurious wakeup" to learn more). So you have to have some condition in there to check, and keep waiting if it's still not time to continue. And to avoid race conditions, that check has to be protected by mutex.
Snippets:
// wait
mDummy.lock();
mStopWaiting = false; // maybe here, if you want to make sure this waits in all cases
while (!mStopWaiting)
{
// note that wait releases the mutex while waiting
mStep1.wait(&mDummy);
}
mDummy.unlock();
// signal end of wait
mDummy.lock();
mStopWaiting = true;
mStep1.wakeOne(); // or wakeAll() maybe depending on other code
mDummy.unlock();
As you can see, that mutex isn't so dummy after all. Note that all access to mStopWaiting has to be protected by this mutex, not just here.
Imagine you want to wait for something to happen. Since that something has to happen in another thread (since this thread is waiting) it has to be protected in some way to avoid race conditions.
Imagine you use the following code:
Acquire a lock.
Check if the thing you want to wait for has happened.
If it has, stop, you're done.
If it hasn't, wait.
Oops. We're still holding the lock. There's no way the thing we're waiting for can happen because no other thread can access it.
Let's try again.
Acquire a lock.
Check if the thing you want to wait for has happened.
If it has, stop, you're done.
If it hasn't, release the lock and wait.
Oops. What if after we release the lock but before we wait, it happens. Then we'll be waiting for something that already happened.
So what we need for step 4 is an atomic "unlock and wait" operation. This releases the lock and waits without giving another thread a chance to sneak in and change things before we can start waiting.
If you don't need an atomic "unlock and wait" operation, don't use QWaitCondition. This is its sole purpose. It takes a QMutex so it knows what to unlock. That QMutex must protect whatever it is the thread is waiting for or your code will be vulnerable to the very race condition QWaitCondition exists to solve for you.
I am new to c++ and I need to solve following problem
/* runs in context of worker thread
void thread1_fun() {
//body
//signal_thread2_fun to unblock
}
/* runs in context of main thread*/
void thread2_fun() {
block on worker thread1_fun and waiting
//body
}
I am sure I need to lock/semaphore/mutex but not sure how?
Thanks in advance.
You can use std::thread::join().
http://en.cppreference.com/w/cpp/thread/thread/join
Edit: If you do not want to wait for the thread to finish, you may be looking for std::condition_variable. http://en.cppreference.com/w/cpp/thread/condition_variable
Please note that you still have to call detach or join on the thread before it is destroyed.
Edit 2: I think a condition variable will work in your scenario, because it expresses the intention that one thread should wait until it gets notified.
For the implementation you need to place a mutex and the condition_variable were both threads can access them. Member variables would work if both are member functions of the same class. Otherwise you can pass them a shared_ptr to a struct with the shared data.
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.
How can I detect when the below code/thread has completed execution in Blackberry:
UiApplication.getUiApplication().invokeAndWait(new Runnable() {
public void run() {
EventInjector.KeyEvent inject = new EventInjector.KeyEvent
(EventInjector.KeyEvent.KEY_DOWN,Characters.ENTER, 0);
inject.post();
inject.post();
}
});
Can I get a notification when this thread has executed so that I can start another thread?
Thanks in advance.
Typically, the join() method is used to determine when a thread has finished. Calling join() typically blocks, so use it with care.
Here is a reference.
You need a synchronized block, here is a short description of how it works.
The "sleeping" thread must lock an object, and call wait() on it.
The other thread locks the same object, and sends a notify() or notifyAll() to wake up the first one.
If you start the thread explicitly (not in this case), you can simply call join() on it, and synchronously wait for it to finish.
- Edit: using join() on a thread
Assuming you already have a runnable object:
Thread myThread = new Thread(myRunnable);
myThread.start();
doOtherStuff();
myThread.join();
But if something goes wrong, you are stuck on the join() call, because BlackBerry has no timeout for this call.