Qt thread ID is equal to MainWindows? (moveToThread) - multithreading

Now I want to create a thread and put in my class "AVC_file" inatance.
But when I print currentThreadId in textBroswer, I found MainWindows's threadID is same with the thread I created. show pitures like below.
Framework::Framework(QWidget * parent) : QMainWindow(parent)
{
ui.setupUi(this);
int threadID = (int)QThread::currentThreadId();
ui.textBrowser->append("Main Tread ID : " + QString::number(threadID));
}
void Framework::on_OpenAVCFile_clicked()
{
QString filePath = QFileDialog::getOpenFileName(
this, tr("Open File"), "C:\\", "AVC File (*.avc)"
);
if (!filePath.isEmpty())
{
QMessageBox::information(this, tr("File Name"), filePath);
}
QFile file(filePath);
if (!file.open(QIODevice::ReadOnly))
{
QMessageBox::information(0, "info", file.errorString());
}
else {
QThread *thread = new QThread(this);
int threadID = (int)thread->currentThreadId();
ui.textBrowser->append("Second Tread ID : " + QString::number(threadID) + "\n");
AVC_File *AVC_file = new AVC_File();
AVC_file->moveToThread(thread);
connect(AVC_file, SIGNAL(requestFileContent(QString)), this, SLOT(addFileContent(QString)));
connect(AVC_file, SIGNAL(requestFileDebug(QString)), this, SLOT(addFileDebug(QString)));
connect(AVC_file, SIGNAL(requestFileCorrectness(bool, int)), this, SLOT(adddFileCorrectness(bool, int)));
connect(AVC_file, SIGNAL(requestNewValue(unsigned int, int)), this, SLOT(addNewValue(unsigned int, int)));
thread->start();
AVC_file->AVC_FileCheck(file);
}
}
Images about my code and results-->
Main Windows, create thread and results
Oh!I also try emit info in my "AVC_file" instance?like below.
void AVC_File::AVC_FileCheck(QFile &file)
{
int threadID = (int)QThread::currentThreadId();
emit requestFileContent("Thread ID by emit" + QString::number(threadID) + "\n");
QTextStream in(&file);
........
........
}
Emit threadID info
Anyone can help me?
BTW, I use visual studio Qt add-in to develop this project.

QThread::currentThreadId() is a static method.
When you call it, it returns the thread ID of the thread that executes it.
In both your cases that's the main thread.

There are several issues that I'll address in random order.
First of all, using thread IDs is bad user experience. Give the threads a descriptive name:
int main(...) {
QApplication app(...);
QThread myThread;
MyObject myObject;
myObject->moveToThread(&myThread);
QThread::currentThread()->setObjectName("mainThread");
myThread.setObjectName("myThread");
...
}
Then use QThread::currentThread()->objectName() to retrieve it. You can also pass QObject* to qDebug() to display the name of the thread:
qDebug() << QThread::currentThread();
Your signal invocation would then become:
QString currentThreadName() {
return QThread::currentThread()->objectName().isEmpty() ?
QStringLiteral("0x%1").arg(QThread::currentThread(), 0, 16) :
QThread::currentThread()->objectName();
}
...
emit requestFileContent(
QStringLiteral("Emitting from thread \"%1\"\n").arg(currentThreadName));
Then, use the above to deal with the thread you've created:
auto thread = new QThread(this);
thread->setObjectName("fileThread");
ui.textBrowser->append(QStringLiteral("Worker thread: \"%1\").arg(thread->objectName()));
auto AVC_file = new AVC_File;
AVC_file->moveToThread(thread);
...
But AVC_FileCheck is invoked from the main thread. Whether that's OK or not depends on how that method is implemented. It needs to be thread-safe, see this question for a discussion of that. TL;DR: The following pattern could be a starting point:
class AVC_file : public QObject {
Q_OBJECT
Q_SLOT void fileCheck_impl(QIODevice * dev) {
dev->setParent(this);
...
}
Q_SIGNAL void fileCheck_signal(QIODevice *);
public:
void fileCheck(QIODevice *dev) { fileCheck_signal(dev); }
AVC_file(QObject *parent = nullptr) : QObject(parent) {
connect(this, &AVC_file::fileCheck_signal, this, &AVC_file::fileCheck_impl);
...
}
};
Finally, your existing AVC_fileCheck API is broken. You pass QFile by reference: this won't ever work since it ceases to exist as soon as on_OpenAVCFile_clicked returns. When AVC_file uses that file in its thread, it's a dangling object reference.
Instead, you must pass the ownership of the file to AVC_file, and pass a pointer to an instance that AVC_file will dispose when done with. Or simply let AVC_file open the file for you!

Related

use a lambda to start a thread which is a class attribute

I would like to assign a name to a thread, the thread itself must do this. The thread is a class member of the class foo.
I would like to start this thread with a lambda but unfortunately I get the error message:
no match for call to '(std::thread) (foo::start()::<lambda()>)
Can someone explain to me where the problem is?
Previously I had created a temporary thread object, and put this with move on the thread "manage", however, I can then give no name.
class foo {
public:
int start()
{
this->manage([this](){
auto nto_errno = pthread_setname_np(manage.native_handle(),"manage"); // Give thread an human readable name (non portable!)
while(1){
printf("do work");
}
});
return 1;
}
private:
int retVal;
std::thread manage;
};
You passed the lambda in a wrong way, after initialization the manage thread can't be initialized again. you should create a new std::thread and assign it.
the following compiles and indeed prints "manage".
class foo {
public:
int start()
{
manage = std::thread([this]{
auto nto_errno = pthread_setname_np(manage.native_handle(),"manage");
char name[16];
pthread_getname_np(pthread_self(), &name[0], sizeof(name));
cout << name << endl;
});
manage.join();
return 1;
}
private:
int retVal;
std::thread manage;
};

Creating new thread causing exception

I have a timer that will create a new thread and wait for the timer to expire before calling the notify function. It works correctly during the first execution, but when the timer is started a second time, an exception is thrown trying to create the new thread. The debug output shows that the previous thread has exited before attempting to create the new thread.
Timer.hpp:
class TestTimer
{
private:
std::atomic<bool> active;
int timer_duration;
std::thread thread;
std::mutex mtx;
std::condition_variable cv;
void timer_func();
public:
TestTimer() : active(false) {};
~TestTimer() {
Stop();
}
TestTimer(const TestTimer&) = delete; /* Remove the copy constructor */
TestTimer(TestTimer&&) = delete; /* Remove the move constructor */
TestTimer& operator=(const TestTimer&) & = delete; /* Remove the copy assignment operator */
TestTimer& operator=(TestTimer&&) & = delete; /* Remove the move assignment operator */
bool IsActive();
void StartOnce(int TimerDurationInMS);
void Stop();
virtual void Notify() = 0;
};
Timer.cpp:
void TestTimer::timer_func()
{
auto expire_time = std::chrono::steady_clock::now() + std::chrono::milliseconds(timer_duration);
std::unique_lock<std::mutex> lock{ mtx };
while (active.load())
{
if (cv.wait_until(lock, expire_time) == std::cv_status::timeout)
{
lock.unlock();
Notify();
Stop();
lock.lock();
}
}
}
bool TestTimer::IsActive()
{
return active.load();
}
void TestTimer::StartOnce(int TimerDurationInMS)
{
if (!active.load())
{
if (thread.joinable())
{
thread.join();
}
timer_duration = TimerDurationInMS;
active.store(true);
thread = std::thread(&TestTimer::timer_func, this);
}
else
{
Stop();
StartOnce(TimerDurationInMS);
}
}
void TestTimer::Stop()
{
if (active.load())
{
std::lock_guard<std::mutex> _{ mtx };
active.store(false);
cv.notify_one();
}
}
The error is being thrown from my code block here:
thread = std::thread(&TestTimer::timer_func, this);
during the second execution.
Specifically, the error is being thrown from the move_thread function: _Thr = _Other._Thr;
thread& _Move_thread(thread& _Other)
{ // move from _Other
if (joinable())
_XSTD terminate();
_Thr = _Other._Thr;
_Thr_set_null(_Other._Thr);
return (*this);
}
_Thrd_t _Thr;
};
And this is the exception: Unhandled exception at 0x76ED550B (ucrtbase.dll) in Sandbox.exe: Fatal program exit requested.
Stack trace:
thread::move_thread(std::thread &_Other)
thread::operator=(std::thread &&_Other)
TestTimer::StartOnce(int TimerDurationInMS)
If it's just a test
Make sure the thread handler is empty or joined when calling the destructor.
Make everything that can be accessed from multiple threads thread safe (specifically, reading the active flag). Simply making it an std::atomic_flag should do.
It does seem like you are killing a thread handle pointing to a live thread, but hard to say without seeing the whole application.
If not a test
...then generally, when need a single timer, recurreing or not, you can just go away with scheduling an alarm() signal into itself. You remain perfectly single threaded and don't even need to link with the pthread library. Example here.
And when expecting to need more timers and stay up for a bit it is worth to drop an instance of boost::asio::io_service (or asio::io_service if you need a boost-free header-only version) into your application which has mature production-ready timers support. Example here.
You create the TestTimer and run it the first time via TestTimer::StartOnce, where you create a thread (at the line, which later throws the exception). When the thread finishes, it sets active = false; in timer_func.
Then you call TestTimer::StartOnce a second time. As active == false, Stop() is not called on the current thread, and you proceed to creating a new thread in thread = std::thread(&TestTimer::timer_func, this);.
And then comes the big but:
You have not joined the first thread before creating the second one. And that's why it throws an exception.

How to send signal from Singleton thread to another thread (Not singleton)

I'm facing a problem while creating a Singleton class with it's own thread that sends signal to another thread which is not a singleton class.
Consumer.h
class Consumer : public QThread
{
Q_OBJECT
public:
explicit Consumer(QObject *parent = 0);
Consumer(Worker *Worker);
signals:
void toMessage(const bool& keepCycle);
public slots:
void getMessage(const QString& str);
private:
int m_counter;
};
Consumer.cpp
Consumer::Consumer(QObject *parent) :
QThread(parent)
{
m_counter = 0;
connect(Worker::Instance(), SIGNAL(sendMessage(QString)), this, SLOT(getMessage(QString)));
connect(this, SIGNAL(toMessage(bool)), Worker::Instance(), SLOT(fromMessage(bool)));
}
// Get's message from Singleton thread if counter > 5 sends signal to terminate cycle in Singleton thread
void Consumer::getMessage(const QString &str)
{
m_counter++;
if(m_counter <= 5) {
qDebug() << "Got message " << m_counter << ": " << str << "\n";
return;
}
else {
emit toMessage(false);
}
}
Singleton is done as follows (suspect it's Not Thread-safe):
template <class T>
class Singleton
{
public:
static T* Instance()
{
if(!m_Instance) m_Instance = new T;
assert(m_Instance != NULL);
return m_Instance;
}
protected:
Singleton();
~Singleton();
private:
Singleton(Singleton const&);
Singleton& operator=(Singleton const&);
static T* m_Instance;
};
template <class T> T* Singleton<T>::m_Instance = NULL;
And Worker Singleton class
class Worker : public QThread
{
Q_OBJECT
public:
explicit Worker(QObject *parent = 0);
void run();
signals:
void sendMessage(const QString& str);
public slots:
void fromMessage(const bool& keepCycle);
private:
volatile bool m_keepCycle;
};
typedef Singleton<Worker> Worker;
Worker.cpp
Worker::Worker(QObject *parent) :
QThread(parent)
{
m_keepCycle = true;
}
void Worker::run()
{
while(true) {
if(m_keepCycle) {
QString str = "What's up?";
ElWorker::Instance()->sendMessage(str);
}
else {
qDebug() << "Keep Alive" << false;
break;
}
}
qDebug() << "Value of keepCycle" << m_keepCycle;
}
void Worker::fromMessage(const bool &keepCycle)
{
m_keepCycle = keepCycle;
qDebug() << "\nMessage FROM: " << keepCycle << "\n";
}
The main.cpp
Consumer consumer;
ElWorker::Instance()->start();
consumer.start();
Can you help me to create thread-safe Singleton and to send signals between threads?
First of all, it is highly recommended to separate worker from it's thread:
class Object : public QObject
{
...
public slots:
void onStarted(); // if needed
void onFinished(); // if needed
...
};
...
mObject = QSharedPointer < Object >(new Object);
mThread = new QThread(this);
mObject->moveToThread(mThread);
connect(mThread, SIGNAL(started()), mObject, SLOT(onStarted())); // if needed
connect(mThread, SIGNAL(finished()), mObject, SLOT(onFinished())); // if needed
mThread->start();
Second of all, there are a lot of ways of creating a singleton. My favourite is this:
Object * obj(QObject *parent = 0)
{
static Object *mObj = new Object(parent);
return mObj;
}
...
obj(this); // creating
obj()->doStuff(); // using
Now, about thread-safety. Sending signals is thread-safe, unless you're sending pointers or non-constant references. Which, according to your code, you are not. So, you should be fine.
UPDATE
Actually, I didn't get how created thread-safe singleton above and I'm
sending a signal from Worker TO Consumer Not a Thread itself? – hiken
Static values inside of function are created and initialized only once, so the first time you call obj function mObj is created and returned and each other time you call it, previously created mObj is returned. Also, I didn't say, it's thread-safe, all I said - I like this way better, then template one, because:
it is simplier
requires less code
works with QObject without problems
Yes, you should send signals from worker class, not thread one. Qt's help has a good example (the first one, not the second one): http://doc.qt.io/qt-5/qthread.html#details. The only thing QThread should be used for - is controlling thread's flow. There are some situations, when you need to derive from QThread and rewrite QThread::run, but your case isn't one of them.

QNetworkAccessManager get called in a QThread because cyclic

I need to call a web request cyclically, so, the easy way to do that is, of course, create a thread and call my request followed by a sleep..
The issue is that I wrote my code and it basically works. When I try to call the get inside a QThread, I don't receive any result, the event associated to the response is never invoked:
class RemoteControl : public QObject {
Q_OBJECT
QNetworkAccessManager* manager;
public:
explicit RemoteControl(QObject* parent = 0);
~RemoteControl() {}
public slots:
void process() {
std::cout << "start" << std::endl;
while (true) {
execute();
std::cout << "called" << std::endl;
sleep(5);
}
}
void execute() {
QUrl url("my request for num of visitors that works..");
QNetworkRequest req;
req.setUrl(url);
req.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/x-www-form-urlencoded"));
QNetworkReply* reply = manager->get(req);
}
void downloadFinished(QNetworkReply* reply) {
std::cout << "finished called" << std::endl;
QByteArray resp = reply->readAll();
std::cout << resp.data() << std::endl;
}
signals:
void finished();
private:
WebRequest* WebReq_;
};
RemoteControl::RemoteControl(bool* enable, LoggerHandle* Log, QObject* parent) : QObject(parent)
{
enable_ = enable;
Log_ = Log;
running_ = false;
manager = new QNetworkAccessManager(this);
connect(manager, SIGNAL(finished(QNetworkReply*)), this,
SLOT(downloadFinished(QNetworkReply*)));
}
int main() {
//.... my code....
QThread* t3 = new QThread;
RemoteContr->moveToThread(t3);
QObject::connect(t3, SIGNAL(started()), RemoteContr, SLOT(process()));
t3->start();
//.... my code....
}
So, what happens is that using this code I didn't get any errors, in the output I can see start and called but never finished called..
it seems that the event downloadFinished is never called.
Can you help me to understand why?
Something wrong in my class RemoteControl?
Thanks
Andrea
You don't need a thread for this. The QNetworkAccessManager is asynchronous, so the calls you're using do not block. Instead of a thread, just do something like this in your main function:
QTimer * timer = new QTimer;
connect(timer, SIGNAL(timeout()), RemoteContr, SLOT(execute());
timer->start(5000); // = 5 seconds
Then, execute is invoked every 5 seconds, which seems to be what you want.
By the way, I think the reason you aren't getting results is that the while loop in process is blocking the thread. You can get rid of the process slot with this approach.

Thread Programming in C++/CLR

I am really struggling with Thread programming in Visual C++/CLR. I have searched a lot and found lots of material on the internet including the official resources however i am still confused. There are very few resources for C++/CLR. Most of them are for C# or old style C++. I try to run this simple code. I choose a new project of type clr console applicatioN and place the following code there but i am getting errors which i am not understading.
// thread_clr.cpp : main project file.
#include "stdafx.h"
using namespace System;
using namespace System;
using namespace System::Threading;
class MessagePrinter;
// class ThreadTester demonstrates basic threading concepts
class ThreadTester
{
static int Main()
{
// Create and name each thread. Use MessagePrinter's
// Print method as argument to ThreadStart delegate.
MessagePrinter printer1 = gcnew MessagePrinter();
Thread thread1 = gcnew Thread ( gcnew ThreadStart( printer1.Print ) );
thread1.Name = "thread1";
MessagePrinter printer2 = gcnew MessagePrinter();
Thread thread2 = gcnew Thread ( gcnew ThreadStart( printer2.Print ) );
thread2.Name = "thread2";
MessagePrinter printer3 = gcnew MessagePrinter();
Thread thread3 = gcnew Thread ( gcnew ThreadStart( printer3.Print ) );
thread3.Name = "thread3";
Console.WriteLine( "Starting threads" );
// call each thread's Start method to place each
// thread in Started state
thread1.Start();
thread2.Start();
thread3.Start();
Console.WriteLine( "Threads started\n" );
} // end method Main
}; // end class ThreadTester
class MessagePrinter
{
private int sleepTime;
private static Random random = gcnew Random();
// constructor to initialize a MessagePrinter object
public MessagePrinter()
{
// pick random sleep time between 0 and 5 seconds
sleepTime = random.Next( 5001 );
}
//controls Thread that prints message
public void Print()
{
// obtain reference to currently executing thread
Thread current = Thread.CurrentThread;
// put thread to sleep for sleepTime amount of time
Console.WriteLine(current.Name + " going to sleep for " + sleepTime );
Thread.Sleep ( sleepTime );
// print thread name
Console.WriteLine( current.Name + " done sleeping" );
} // end method Print
} // end class MessagePrinter
Please help. Or better still please guide me to some tutorials or something to that affect. I understand SO is not a tutorial site and i am not asking one but i would appreciate if some one could atleast point out the resources for C++/CLR thread. C++/CLR Winform Threads. Would really appreciate it
Regards
Some errors are:
'printer1' uses undefined class 'MessagePrinter' 'Print' : is not a
member of 'System::Int32' 'System::Threading::ThreadStart' : a
delegate constructor expects 2 argument(s)
'System::Threading::Thread::Thread' : no appropriate default
constructor available 'System::Threading::Thread::Thread' : no
appropriate default constructor available 'syntax error : 'int' should
be preceded by ':' 'cannot declare a managed 'random' in an unmanaged
'MessagePrinter'may not declare a global or static variable, or a
member of a native type that refers to objects in the gc heap
'MessagePrinter::random' : you cannot embed an instance of a reference
type, 'System::Random', in a native type 'MessagePrinter::random' :
only static const integral data members can be initialized within a
class 'MessagePrinter' should be preceded by ':' 'void' should be
preceded by ':'
I fixed that code for you, but let me say one thing first: you really need to learn the basics first. This was not even C++/CLI code and you did not find or could not fix the most glaring syntax errors. Forget threads for a while, they are difficult. Learn basic stuff first.
#include "stdafx.h"
using namespace System;
using namespace System::Threading;
ref class MessagePrinter
{
private:
int sleepTime;
static Random^ random = gcnew Random();
// constructor to initialize a MessagePrinter object
public:
MessagePrinter()
{
// pick random sleep time between 0 and 5 seconds
sleepTime = random->Next( 5001 );
}
//controls Thread that prints message
void Print()
{
// obtain reference to currently executing thread
Thread^ current = Thread::CurrentThread;
// put thread to sleep for sleepTime amount of time
Console::WriteLine(current->Name + " going to sleep for " + sleepTime );
Thread::Sleep ( sleepTime );
// print thread name
Console::WriteLine( current->Name + " done sleeping" );
} // end method Print
}; // end class MessagePrinter
int main()
{
// Create and name each thread. Use MessagePrinter's
// Print method as argument to ThreadStart delegate.
MessagePrinter^ printer1 = gcnew MessagePrinter();
Thread^ thread1 = gcnew Thread(gcnew ThreadStart( printer1, &MessagePrinter::Print ) );
thread1->Name = "thread1";
MessagePrinter^ printer2 = gcnew MessagePrinter();
Thread^ thread2 = gcnew Thread ( gcnew ThreadStart( printer2, &MessagePrinter::Print ) );
thread2->Name = "thread2";
MessagePrinter^ printer3 = gcnew MessagePrinter();
Thread^ thread3 = gcnew Thread ( gcnew ThreadStart( printer3, &MessagePrinter::Print ) );
thread3->Name = "thread3";
Console::WriteLine( "Starting threads" );
// call each thread's Start method to place each
// thread in Started state
thread1->Start();
thread2->Start();
thread3->Start();
Console::WriteLine( "Threads started\n" );
Console::ReadLine();
return 0;
}
Be Aware that you leave the Main function and therefor all threads will be terminated... so place an Console.ReadLine() in the last line of your "main"...
Also: Your source code is C# and not C++/CLI...

Resources