QThread weird behaviour [closed] - c++

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a QThread running some code and I wanted it to do exit nicely and do some cleanings so the code goes as:
testdevice.h
class testDevice : public QThread
{
Q_OBJECT
... // some definitions
protected:
void run(void);
private:
hid_device *handle;
bool abort;
public:
~testDevice(void);
};
testdevice.cpp
testDevice::~testDevice(void)
{
mutex.lock();
abort = true;
mutex.unlock();
wait();
if (handle != NULL)
{
hid_close(handle);
}
hid_exit();
}
void testDevice::run(void)
{
while(true)
{
mutex.lock();
if(abort)
{
return;
}
mutex.unlock();
if (_connected)
{
//... more code
}
else // Case device is not connected
{
emit deviceConnected(_connected);// A breakpoint in here is not triggered after abort is true
handle = hid_open(TEST_VID, TEST_PID, NULL); // this is where VS2010 shows the error "Unhandled exception at 0x71241a95 in project.exe: 0xC0000005: Access violation."
//...code continues
The behaviour I was expecting was run() to be called and when ~testDevice() destructor is called abort is set to true and wait blocks the destructor, and runreturns and then the destructor continues.
What is happening is that run() is called and when I close the application the destructors ~testDevice() is called and abort is set to true and wait() returns and the destructor finishes...BUT then run() keeps running and I get Unhandled exception at 0x71241a95 in project.exe: 0xC0000005: Access violation.....I am running this as VS2010 debug, if I place breakpoints I get this all the time, but with no breakpoints I just got this once in a while...any clues?
Something weird is that when I place a breakpoint in abort = true; sometimes the first breakpoint that hits in there has a small blue '!' sign, and the second time it hits is a regular all red one. The same happens for the breakpoint at emit deviceConnected(_connected); but this is kinda random as well...I dont know what this '!' means...could all of this be a debug problem?
My general suspicion is that HIDAPI is running in a separate thread and it has its own bugs when someone call hid_exit(); maybe hid_read(); continues to run and since hid_quit(); was called, hid_read(); looses some pointers and doesnt close...just a wild shot and to confirm this I need some developer at the HIDAPI to come foward and say something...I hope they read this

You seem to be using QThread in a custom way rather than the usual start() and quit() execution. The best would be that in an ideal world if you could refactor your code using quit() for quiting a QThread since that would be closer to the signal/slot mechanism of this QObject subclass.
However, I agree that it is not always possible. I cannot yet tell you based on your few lines you provided that it would make sense in this particular case, but at least I would encourage you to think about it.
Also, you could possibly use the QWaitCondition for waiting for something to happen rather than low-level or/and custom wait() calls.
As for quickly working around the issue you are facing if the issue at hand is compiler optimization of a boolean value like putting it into the cache, you could try having making it atomic by using the std::atomic (C++11) or QAtomicInt option. This will make sure that the compiler cannot optimize the reads and writes out.
You would write something like this with the std typedef:
std::atomic_bool abort;
If you need to support pre C++-11 compilers as well as Qt 4, you would use the Qt class like this:
QAtomicInt abort;

Related

QThread Destruction on closing

hello guys I have a worker thread in qt with C++ , if I use workerThreadPointer->quit(); in mainwindow destruction ~mainwindow{} or in workerthread destruction its self when I close the program I get this error QThread: Destroyed while thread is still running but if I use workerThreadPointer->terminate(); I wont get any errors but terminate() method is not recommended so how can I use quite on the closing of program with out crashing and getting erorrs
I actually used this and it worked but is it the best way ??
bool asghar;
workerThread::workerThread(){
}
workerThread::~workerThread(){
quit();
requestInterruption();
asghar=0;
wait(100);
}
void workerThread::run(){
asghar=1;
while(asghar==true){
do something
}
}
which is basically I force it to gets out of the while loop with a boolian variable but Im not sure its the best option btw if I change that 100 in wait to 10 , its not ganna work.
I'm not sure if it's a typo because you only wrote pseduo-code or if it's actually like this in your program. But while(asgar=true) doesn't do what you think it does. The classic = vs == bug.
void workerThread::run(){
asghar=1;
while(asghar=true){ // bug
do something
}
Should be this:
void workerThread::run(){
asghar=1;
while(asghar == true) { // fixed
do something
}
Also the compiler is free to optimize away the check to asghar since its access is not thread safe. Consider changing asghar to be of type std::atomic<bool> or wrap the assignment and check calls with a mutex.
Add print/log statement around the assignment and comparison checks to asghar to see what's going on.

abort() is called when I try to terminate a std::thread [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 6 months ago.
Improve this question
Note: I'm using WinForms & C++17.
So I was working on a school project. I have this function:
bool exs::ExprSimplifier::simplify()
{
bool completed = false;
std::thread thread1(&ExprSimplifier::internalSimplity, this, std::ref(completed));
while (true)
{
if (completed)
{
thread1.~thread(); // calls abort()
return true;
}
if (GetAsyncKeyState(27))
{
thread1.~thread(); // calls abort()
return false;
}
}
}
Basically what I want is to run the following function:
// at the end of this function, I set completed = true
void exs::ExprSimplifier::internalSimplity(bool& completed)
..on another thread. I also want to check while the function's doing it's thing and the user pressed esc key, the thread terminates. But there's where I'm facing issues. This:
thread1.~thread();
..is calling abort(), crashing the application. Now what I think is that this is due to some scope thing of std::thread, but I'm not really sure.
Questions:
What's the reason for this?
What can I do to fix this?
You can't terminate threads - end of story. In the past, they tried to make it so you could terminate threads, but they realized it's impossible to do it without crashing, so now you can't. (E.g. Windows had a TerminateThread function, because it's old. C++ doesn't have it, because C++ threads are new)
The only thing you can do is set a variable that tells the thread to stop, and then wait for it to stop.
~thread doesn't terminate threads, anyway. All it does is check that you remembered to call join or detach, and if you forgot to call one of them, it aborts, as you are seeing.
What you typically want to do is something along this general line:
class doWhatever {
std::atomic<bool> stop {false};
std::thread t;
public:
void run() {
t = std::thread([] {
while (!stop) {
doSomeProcessing();
}
});
}
void stop() {
stop = true;
}
~doWhatever() {
if (t.joinable())
t.join();
}
};
Exactly what you're going to do in doSomeProcessing obviously varies depending on what you really want your thread to do. Some threads have a queue of incoming tasks, and check the variable before processing each incoming task. Others have one long task to do, but if they do there's typically some loop there that you can check the variable at each iteration.
At least in my opinion, for a lot of situations, the ideal is that you check whether you've been asked to shut down something like once very 100 ms. This gives a nice balance--to a person, shutting down with 100 ms of telling it to looks nearly instantaneous, but you're still checking it infrequently enough that it doesn't affect execution speed enough to notice.
If you have a new enough compiler to support it, you may prefer to use std::jthread instead of std::thread. It basically includes an equivalent of the std::atomic<bool> in the thread object.

Read/Write lock using only critical section causes deadlock [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
After going through this question with the same title and its answers, I thought to try something that should really work only using critical section and thus should be much faster that existing solutions (which use other kernel objects too like mutex or semaphore)
Here are my Read/Write lock/unlock functions:
#include <windows.h>
typedef struct _RW_LOCK
{
CRITICAL_SECTION readerCountLock;
CRITICAL_SECTION writerLock;
int readerCount;
} RW_LOCK, *PRW_LOCK;
void InitLock(PRW_LOCK rwlock)
{
InitializeCriticalSection(&rwlock->readerCountLock);
InitializeCriticalSection(&rwlock->writerLock);
}
void ReadLock(PRW_LOCK rwlock)
{
EnterCriticalSection(&rwlock->readerCountLock); // In deadlock 1 thread waits here (see description below)
if (++rwlock->readerCount == 1)
{
EnterCriticalSection(&rwlock->writerLock); // In deadlock 1 thread waits here
}
LeaveCriticalSection(&rwlock->readerCountLock);
}
void ReadUnlock(PRW_LOCK rwlock)
{
EnterCriticalSection(&rwlock->readerCountLock);
if (--rwlock->readerCount == 0)
{
LeaveCriticalSection(&rwlock->writerLock);
}
LeaveCriticalSection(&rwlock->readerCountLock);
}
int WriteLock(PRW_LOCK rwlock)
{
EnterCriticalSection(&rwlock->writerLock); // In deadlock 3 threads wait here
}
void WriteUnlock(PRW_LOCK rwlock)
{
LeaveCriticalSection(&rwlock->writerLock);
}
And here is a thread function. After calling InitLock (&g_rwLock); from main I created FIVE threads to try these locks.
void thread_function()
{
static int value = 0;
RW_LOCK g_rwLock;
while(1)
{
ReadLock(&g_rwlLock);
BOOL bIsValueOdd = value % 2;
ReadUnlock(&g_rwlLock);
WriteLock(&g_rwlLock);
value ++;
WriteUnlock(&g_rwlLock);
}
}
Ideally this code should keep running forever without any trouble. But to my disappointment, it doesn't run always. Some times it lands up in deadlock. I compiled this and ran it on Windows XP. To create threads using threadpool, I am using third party library. Hence cannot give here all that code which involves lots of initializing routines and other stuff.
But to cut the story short, I like to know if anyone by looking at the code above can point out what is wrong with this approach?
I've commented in the code above where each thread (out of FIVE threads) keeps waiting when deadlock happens. (I found it out by attaching debugger to the deadlocked process)
Any inputs/suggestions would be really great as I've stuck over this for quite some time now (In the greed of making my code run faster than ever).
Spotted two things so far:
You initialize the critical sections in every thread, which is not allowed (behavior is undefined)
You can't leave a critical section in a different thread from the one that entered it ("If a thread calls LeaveCriticalSection when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection to wait indefinitely.")
The latter fits the deadlock you see.
Once you have multiple readers concurrently, you don't control which order they call ReadUnlock, so you can't ensure that the first thread in, which is the only one allowed to call LeaveCriticalSection, is the last one out.
This way it cannot run correctly.
lets 1 thread enter ReadLock(), let it pass ++ instruction but pause it before entering writer CS
another thread enters WriteLock() and successfuly enters writerCS
so now we have readers count = 1 and running writer at the same time. note that reader is deadlocked on EnterCriticalSection(&rwlock->writerLock)

Catching Exceptions with Pthreads

While this question isn't limited to the OpenKinect Libraries, it is the best example I could come up with for showing this off.
In the C++ Wrapper for OpenKinect, whenever something goes wrong it throws a runtime_error exception. This example is from libfreenect.hpp. The thread is created in the constructor of the class.
// Do not call directly, thread runs here
void operator()() {
while(!m_stop) {
if(freenect_process_events(m_ctx) < 0) throw std::runtime_error("Cannot process freenect events");
}
}
static void *pthread_callback(void *user_data) {
Freenect* freenect = static_cast<Freenect*>(user_data);
(*freenect)();
return NULL;
}
My question is simply: is it possible to catch these errors somehow and handle them?
Ordinarily, I would handle the exceptions, or rewrite the code: I don't like having programs crash because of exceptions, I would rather handle them cleanly if I know it is possible for them to occur. There are some libraries that do similar things that I cannot rewrite, hence why I came around to asking this question.
You have to define more clearly what are the thread's responsibilities. I'm guessing it feeds some messages to some other threads, through some kind of pipe or concurrent queue. In that case just change your message class to store exception information (std::exception_ptr). When you access the data in the message, first check if contains an exception; if so, call std::rethrow_exception().
A similar mechanism is used in std::future(); either you get() the promised value out of it, or an exception is raised while trying to do so, that came from the other thread. Search for std::async() examples to see it in action.

boost thread error

I have a program that uses boost threads. The program has start and stop functionality. When the program is started I create a boost thread that does some processing. When the program is stopped I call join on this thread and delete the thread's pointer. My program starts and stops correctly the first time; however, when I try to start my program a second time I fail an assertion inside of boost (when newing the processing thread) and the following is output on my screen
/root/src/boost.cmake/libs/thread/src/pthread/once.cpp:46: unsigned long &boost::detail::get_once_per_thread_epoch(): Assertion`!pthread_setspecific(epoch_tss_key,data)' failed.
I know that my join is working correctly because when the processing thread exits I output a message to my console. Does anyone know why this might happen?
An extra note... I have played around with my code a little bit and the methodology that I am using to clean up my boost threads appears to work in other parts of my program (for example, if I create the boost::thread in the parent class). However, it fails every time in the child class (which is an abstract class).
My start and stop methods looks like this...
void ThreadMethod()
{
while(_runningThread)
{
}
}
void Start()
{
_runningThread = true;
_thread = boost::make_shared<boost::thread>(&TestChildVirtualClass::ThreadMethod, this);
};
void Stop()
{
_runningThread = false;
_thread->join();
if( _thread )
{
_thread.reset();
}
};
However, I am having trouble recreating this issue in a test program (although it occurs every time in my actual program).
The error could be a bug on Boost.Thread as there are some holes in the call_once implementation (#5752 boost::call_once() is unreliable on some platforms - see https://svn.boost.org/trac/boost/ticket/5752). This of course depends on which platform you are running your program.
Of course I maybe wrong.
You should also protect the access to _runningThread.