Why console app hangs when using a shared dll that containg static variable that use mutex? - multithreading

I have a shared dll library that contains a class as below :
inside A.dll >> Header File :
class API ErrorHandler
{
public:
ErrorHandler();
virtual ~ErrorHandler();
protected:
static ErrorHandler* defaultHandler();
private:
static ErrorHandler* _pHandler;
static std::mutex _mutex;
};
source(.cpp)
ErrorHandler* ErrorHandler::_pHandler = ErrorHandler::defaultHandler();
std::mutex ErrorHandler::_mutex;
ErrorHandler::ErrorHandler()
{
}
ErrorHandler::~ErrorHandler()
{
}
ErrorHandler* ErrorHandler::defaultHandler()
{
static SingletonHolder<ErrorHandler> sh;
return sh.get(); **<<====== here we get hanged** see the declaration of get
}
SingletoneHolder header file
template <class S>
class SingletonHolder
{
public:
SingletonHolder():
_pS(0)
{
}
~SingletonHolder()
{
delete _pS;
}
S* get()
{
std::lock_guard<std::mutex> lock(_m); <===== cause thread hang
if (!_pS) _pS = new S;
return _pS;
}
private:
S* _pS;
std::mutex _m;
};
After building the above code (every thing related to compiler setting configured correctly) now I want to use it in my console app.
After running console app, app hangs and never reach to main function.
Why std::lock_guard<std::mutex> lock(_m); hangs and prevent main thread to continue executing?
What is alternative?
I am using VS2013 Update5.
content of main file :
#include "ErrorHandler" <== when remove this include app run correctly
#include <iostream>
int main()
{
getchar();
return 0;
}

First, you should post exact contents of the main - with an empty main everything works. Things go south when the ErrorHandler class is being instantiated inside main.
Second, the initialization of your static members occurs inside __DllMainCRTStartup and as stated in the SO question I marked as duplicate, MSDN states that using synchronization primitives from __DllMainCRTStartup can cause a deadlock. A possible solution is to switch to a critical secion.

Related

QSerialPort with no GUI, no thread: QObject::startTimer: Timers can only be used with threads started with QThread

I'm doing a DLL with no GUI (TEMPLATE = lib), using QSerialPort. I don't create threads and I don't need any: I have no GUI and having a blocking serial port operation is no problem, it is what I want.
When doing:
while (!serial_uart->isWritable());
while (!serial_uart->write(frame));
I get:
QObject::startTimer: Timers can only be used with threads started with QThread
Question: how to use QSerialPort in a library without GUI without triggering this error?
Note: I first thought the problem was coming from serial_uart->waitForReadyRead(timeout) but even without this and only serial_uart->write() I already have this problem.
Minimal reproducible DLL example:
test.cpp
#include "test.h"
extern "C" {
__declspec(dllexport) Test* new_Test() { return new Test(); }
__declspec(dllexport) void DoTest(Test *t) { t->DoTest(); }
}
Test::Test() :QObject()
{
qDebug("Hello");
}
void Test::DoTest()
{
this->serialport = new QSerialPort();
this->serialport ->setPortName("COM12");
this->serialport->setBaudRate(QSerialPort::Baud19200);
this->serialport->open(QIODevice::ReadWrite);
while (!this->serialport->isWritable());
while (!this->serialport->write("hello"));
}
test.h
#include <QSerialPort>
class Test : public QObject
{
Q_OBJECT
public:
Test();
void DoTest();
QSerialPort *serialport;
};
test.pro
TEMPLATE = lib
TARGET = test
QT += serialport
INCLUDEPATH += .
HEADERS += test.h
SOURCES += test.cpp
When I call the release/test.dll from Python I have this:
from ctypes import *
dll = CDLL(r"release\test.dll")
dll.new_Test.restype = c_void_p
dll.new_Test.argtypes = []
dll.DoTest.restype = None
dll.DoTest.argtypes = [c_void_p]
t = dll.new_Test()
dll.DoTest(t)
Hello
QObject::startTimer: Timers can only be used with threads started with QThread
Most of the QIODevice based classes (like Qt sockets or serial port) want to live in a Qt based thread and also their functions needs to be called from the same thread where the object was created.
For that reason I've usually solved this by:
Create wrapper class (QObject based with Q_OBJECT macro for signal/slot functionality) for the QIODevice based class you are about to use. For each function you are planning on using create a slot function on your wrapper class which then calls the equivalent funtion in the QIODevice:
qint64 MySerialPort::write(const QByteArray &data)
{
// m_serialPort is created with new QSerialPort in constructor of MySerialPort.
return m_serialPort->write(data);
}
Create a QThread class that in its run function creates an instance of MySerialPort (with new MySerialPort) and just calls exec() after that. Now MySerialPort lives in an event loop and is able to send and receive signals/slots.
void MySerialPortThread::run()
{
m_serialPort = new MySerialPort();
exec();
delete m_serialPort; // Automatic deletion after thread is stopped.
}
The thread could also return a pointer to the instance for easier access from outside to connect signals and slots.
MySerialPort* MySerialPortThread::serialPort()
{
return m_serialPort; // Instance of MySerialPort class
}
In your main code create signals that match the slots of the MySerialPort and connect them.
signals:
qint64 writeSerial(const QByteArray& data);
void MyMainClass::connectSignalsAndSlots()
{
MySerialPort* serialPort = m_serialThread->serialPort();
connect(this, &MyMainClass::writeSerial, serialPort, &MySerialPort::write, Qt::BlockingQueuedConnection); // Use either QueuedConnection or BlockingQueuedConnection to force the execution of the slot to the MySerialThread.
}
Emit the signals to access the QSerialPort.
emit writeSerial(dataByteArray);

dlclose() static destructors run at different times if function is virtual

I'm using dlopen() and dlclose() to load and unload a module. The module contains some static data which needs to be destructed when dlclose() is called. However I'm finding that under certain circumstances dlclose() does not call the destructors - instead they are only called when main() exits.
I've boiled my code down to this. I have a class which contains a virtual function getType() defined inside the class, making reference to static data. I also have a StaticDestructionChecker object which just prints when the static constructors and destructors are being called. Finally I have a main() function that loads everything else via dlopen(), closes it via dlclose() and prints when main() is finished:
module1.h
#ifndef MODULE1_H
#define MODULE1_H
class MyClass
{
public:
MyClass();
virtual ~MyClass();
virtual int& getType() const
{
static int t(123);
return t;
}
};
#endif // MODULE1_H
module1.cpp
#include <stdio.h>
#include "module1.h"
MyClass::MyClass()
{
}
MyClass::~MyClass()
{
}
class StaticDestructionChecker
{
public:
StaticDestructionChecker()
{
printf("Constructing static data\n");
}
~StaticDestructionChecker()
{
printf("Destructing static data\n");
}
};
StaticDestructionChecker checker;
main:
#include <dlfcn.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
void* handle = dlopen("module1.so", RTLD_NOW);
if (!handle) printf("dlopen error: %s\n", dlerror());
dlclose(handle);
printf("end of main\n");
return 0;
}
Running all this as-is causes the static data to be destructed after main terminates, ie the output is:
Constructing static data
end of main
Destructing static data
The problem is with the virtual/static combo in getType(). If I change getType() to be non-virtual OR if I remove the "static int t", the destructors get called when expected, ie output is:
Constructing static data
Destructing static data
end of main
Is there a way to get the correct destruction order while still keeping the virtual/static code? FYI this is a simplified version of a sort of custom RTTI system, where getType() is automatically generated via a DECLARE_xxx macro, so I don't want to move the implementation into the cpp file because there would need to be a second macro call in there too.
I am using GCC 4.8 on Ubuntu 12.
Thanks
See dlclose() doesn't work with factory function & complex static in function?
If you use gold linker than passing --no-gnu-unique flag when linking module1.so fixes the problem:
]$ g++ -o module1.so -shared -fPIC -Wl,--no-gnu-unique module1.cpp
]$ g++ main.cpp -ldl
]$ LD_LIBRARY_PATH=. ./a.out
Constructing static data
Destructing static data
end of main
I don't know what are other consequences of using that flag.

C++/CLI multiple errors

I am getting multiple, confusing errors when building this school assignment and am hoping for some direction on what might be the problem. I wouldn't normally write it like this, but I put everything into one file as I try to debug this. Using Visual Studios Express 2012. I'm getting over 30 errors when I build, so I'm sure there is something fundamental that I am simply overlooking. Just a suggestion please, not looking for anyone to do my homework. Thanks
#include "stdafx.h"
#include <Windows.h>
#include <iostream>
#include "MessageDisplayClass.h"
#include "LogMessageClass.h"
#include "TimerEventArgs.h"
using namespace System;
ref class CustomTimerClass
{
private:
static bool stopFlag = false;
// create instance of TimerEventArgs
TimerEventArgs^ timerEvent;
public:
CustomTimerClass(void)
{
}
delegate void CustomTimerClass::TimerAlarmHandler(/*Object^ sender, TimerEventArgs^ args*/);
event CustomTimerClass::TimerAlarmHandler^ OnTimerAlarm;
property bool StopFlag
{
bool get(void)
{
return stopFlag;
}
void set(bool b)
{
stopFlag = b;
}
}
void run()
{
Sleep(1000);
raiseTimerAlarm();
}
void OnStart()
{
// create instances of DisplayMessageClass and LogMessageClass classes
DisplayMessageClass^ messageDisplayer = gcnew DisplayMessageClass(this);
LogMessageClass^ messageLogger = gcnew LogMessageClass(this);
// display and log messages concerning this event
messageDisplayer->displayMessage(this, timerEvent);
messageLogger->logMessage(this, timerEvent);
}
void raiseTimerAlarm()
{
// create instance of TimerEventArgs and get time of instance creation
timerEvent = gcnew TimerEventArgs();
String^ eventTime = timerEvent->EventTime;
// tie this instance of CustomTimerClass to OnTimerAlarm event and start event
this->OnTimerAlarm += gcnew TimerAlarmHandler(this, &CustomTimerClass::OnStart);
OnTimerAlarm();
}
};
ref class MainProgram
{
int main(array<System::String ^> ^args)
{
CustomTimerClass^ timerClass = gcnew CustomTimerClass();
DisplayMessageClass^ messageClass = gcnew DisplayMessageClass();
LogMessageClass^ logerClass = gcnew LogMessageClass();
timerClass->run();
return 0;
}
};
At the point you're trying to use the various classes, the compiler doesn't know about them yet. Move your main() function to the end of the file. Or better, split your class definitions in their own header files and then include them in your main source file.
There are other related problems too. For example, you're trying to use the TimerEventArgs class before the compiler knows about it. So you need to move the class definition up. This is why it's best to have each class in its own header file, and then include it where needed. Though it's not strictly unnecessary, if you declare/define everything in the correct order.
Other than wrong order of declarations, it looks like the problem is that the compiler doesn't recognize the ^ bit, which suggests you're not compiling as C++/CLI. Righ-click the project in Solution Explorer and go to Configuration Properties -> General, and make sure that Common Language Runtime Support is set to Common Language Runtime Support (/clr).
For the benefit of anyone else (other newbies): As it turns out, my suspicion that the problem lay in the fact that some of the classes were "#including" each other was the problem. Using forward declarations, combined with having to create a separate class altogether to act as a variable storage handler was the solution to my problem.
Here are the two classes that were giving me the biggest problem, corrected to function correctly:
/*
CustomTimerClass.h
*/
#include "StdAfx.h"
#include "LogMessageClass.h"
#include "MessageDisplayClass.h"
#include "TimerEventArgs.h"
#include "Variables.h"
//ref class MessageDisplayClass;
//ref class Variables;
using namespace System;
ref class CustomTimerClass
{
private:
static bool stopFlag = false;
// create instance of TimerEventArgs
TimerEventArgs^ timerEvent;
// create instance of MessageDisplayClass and LogMessageClass
MessageDisplayClass^ messageDisplayer;
LogMessageClass^ messageLogger;
Variables^ flagVariable;
public:
CustomTimerClass(void)
{
}
delegate void CustomTimerClass::TimerAlarmHandler();
event CustomTimerClass::TimerAlarmHandler^ OnTimerAlarm;
property bool StopFlag
{
bool get(void)
{
return stopFlag;
}
void set(bool b)
{
stopFlag = flagVariable->Flag;
}
}
void run()
{
Sleep(1000);
raiseTimerAlarm();
}
void OnStart()
{
// create instances of DisplayMessageClass and LogMessageClass classes
messageDisplayer = gcnew MessageDisplayClass(this, flagVariable);
messageLogger = gcnew LogMessageClass(this);
// display and log messages concerning this event
messageDisplayer->displayMessage(this, timerEvent);
messageLogger->logMessage(this, timerEvent);
}
void raiseTimerAlarm()
{
// create instance of TimerEventArgs and get time of instance creation
timerEvent = gcnew TimerEventArgs();
String^ eventTime = timerEvent->EventTime;
// tie this instance of CustomTimerClass to OnTimerAlarm event and start event
this->OnTimerAlarm += gcnew TimerAlarmHandler(this, &CustomTimerClass::OnStart);
OnTimerAlarm();
}
};
/*
MessageDisplayClass serves to display a message that
represents the time at which the TimerEventArgs class is
instantiated. This time is returned through a function
of TimerEventArgs class.
*/
#pragma once
#include "stdafx.h"
#include <iostream>
#include "TimerEventArgs.h"
#include "Variables.h"
using namespace System;
ref class CustomTimerClass; // FORWARD DECLARATION HERE CAN
// ONLY BE USED FOR REFERENCE. CANNOT
// BE USED WHEN METHODS OF THE CLASS
// ARE CALLED
ref class MessageDisplayClass
{
private:
CustomTimerClass^ customTimerRef;
// Variables CLASS CREATED SOLELY TO ACT AS GO-BETWEEN BETWEEN
// MessageDisplayClass and CustomTimerClass
Variables^ variableRef;
static int counter;
public:
// constructor
MessageDisplayClass(CustomTimerClass^ CustomTimerClassInput, Variables^ variableReference)
{
customTimerRef = CustomTimerClassInput;
variableRef = gcnew Variables (CustomTimerClassInput);
}
void displayMessage(Object^ sender, TimerEventArgs^ timer)
{
counter ++;
if (counter > 0)
{
variableRef->Flag = true;
Console::WriteLine("Message: an event occured at time stamp: " + timer->EventTime);
}
}
};

Boost library and CreateThread win API

I have a class such as :
class MyStreamReader
{
public:
MyStreamReader(MyPramameter myPram) {.....}
~MyStreamReader() {}
DWORD WINAPI ReaderThread(LPVOID *lpdwThreadParam )
{
//....
}
};
and i want to call ReaderThread with WinAPI CreateThread. But CreateThread wants ReaderThread function wants a static function.
In some forms it is said that this is possible with boost library such as :
CreateThread(NULL, 0, boost::bind(&MyStreamReader::ReaderThread,this),
(void*)&myParameterObject), 0, NULL);
But i got compilation error:
'CreateThread' : cannot convert parameter x from 'boost::_bi::bind_t<R,F,L>'
to 'LPTHREAD_START_ROUTINE'
So as a result my questions:
Is it possible to call non-static function of a class from
CreateThread using boost lib(or any other method)
If not any C++ THREADing librray you may recomend(for visual C++) which i can call-run non static member function of a class as a thread?
Best Wishes
Update:
So first question: It seesm that it is impossible to call non-static c++ member function from CreateThread win API...
So any recomandations for C++ Multithreading lib whic is possible to call non-static functions as threads...
Update 2:
Well i try boost thread lib...seems it works...
MyStreamReader* streamReader = new MyStreamReader(myParameters);
boost::thread GetStreamsThread
( boost::bind( &MyStreamReader::ReaderThread, streamReader ) );
or (no need for bind)
boost::thread GetStreamsThread(&MyStreamReader::ReaderThread, streamReader);
AND in order to use boost::thread i update my class definition as:
class MyStreamReader
{
public:
MyStreamReader(MyPramameter myPram) {.....}
~MyStreamReader() {}
void ReaderThread()
{
//....
}
};
One common answer to this is to use a static "thunk":
class Worker
{
public :
static DWORD Thunk(void *pv)
{
Worker *pThis = static_cast<Worker*>(pv);
return pThis->DoWork();
}
DWORD DoWork() { ... }
};
...
int main()
{
Worker worker;
CreateThread(NULL, 0, &Worker::Thunk, &worker);
}
You can, of course, pack more parameters into your call to pv. Just have your thunk sort them out correctly.
To answer your question more directly, boost::bind doesn't work with the Winapi that way. I would advise using boost::thread instead, which does work with boost::bind (or, if you have a C++0x compiler, use std::thread with std::bind).

Looking for an optimum multithread message queue

I want to run several threads inside a process. I'm looking for the most efficient way of being able to pass messages between the threads.
Each thread would have a shared memory input message buffer. Other threads would write the appropriate buffer.
Messages would have priority. I want to manage this process myself.
Without getting into expensive locking or synchronizing, what's the best way to do this? Or is there already a well proven library available for this? (Delphi, C, or C# is fine).
This is hard to get right without repeating a lot of mistakes other people already made for you :)
Take a look at Intel Threading Building Blocks - the library has several well-designed queue templates (and other collections) that you can test and see which suits your purpose best.
If you are going to work with multiple threads, it is hard to avoid synchronisation. Fortunately it is not very hard.
For a single process, a Critical Section is frequently the best choice. It is fast and easy to use. For simplicity, I normally wrap it in a class to handle initialisation and cleanup.
#include <Windows.h>
class CTkCritSec
{
public:
CTkCritSec(void)
{
::InitializeCriticalSection(&m_critSec);
}
~CTkCritSec(void)
{
::DeleteCriticalSection(&m_critSec);
}
void Lock()
{
::EnterCriticalSection(&m_critSec);
}
void Unlock()
{
::LeaveCriticalSection(&m_critSec);
}
private:
CRITICAL_SECTION m_critSec;
};
You can make it even simpler using an "autolock" class you lock/unlock it.
class CTkAutoLock
{
public:
CTkAutoLock(CTkCritSec &lock)
: m_lock(lock)
{
m_lock.Lock();
}
virtual ~CTkAutoLock()
{
m_lock.Unlock();
}
private:
CTkCritSec &m_lock;
};
Anywhere you want to lock something, instantiate an autolock. When the function finishes, it will unlock. Also, if there is an exception, it will automatically unlock (giving exception safety).
Now you can make a simple message queue out of an std priority queue
#include <queue>
#include <deque>
#include <functional>
#include <string>
struct CMsg
{
CMsg(const std::string &s, int n=1)
: sText(s), nPriority(n)
{
}
int nPriority;
std::string sText;
struct Compare : public std::binary_function<bool, const CMsg *, const CMsg *>
{
bool operator () (const CMsg *p0, const CMsg *p1)
{
return p0->nPriority < p1->nPriority;
}
};
};
class CMsgQueue :
private std::priority_queue<CMsg *, std::deque<CMsg *>, CMsg::Compare >
{
public:
void Push(CMsg *pJob)
{
CTkAutoLock lk(m_critSec);
push(pJob);
}
CMsg *Pop()
{
CTkAutoLock lk(m_critSec);
CMsg *pJob(NULL);
if (!Empty())
{
pJob = top();
pop();
}
return pJob;
}
bool Empty()
{
CTkAutoLock lk(m_critSec);
return empty();
}
private:
CTkCritSec m_critSec;
};
The content of CMsg can be anything you like. Note that the CMsgQue inherits privately from std::priority_queue. That prevents raw access to the queue without going through our (synchronised) methods.
Assign a queue like this to each thread and you are on your way.
Disclaimer The code here was slapped together quickly to illustrate a point. It probably has errors and needs review and testing before being used in production.

Resources