简体   繁体   中英

C++ thread connect in Qt

I am starting to learn threads in the C++11 standard in Qt.I can't include library ,no such of directory For example, I have the following simple code:

#include <QCoreApplication>
#include <thread>
#include <iostream>

using namespace std;
void func();

int main(int argc, char *argv[])
{
   QCoreApplication a(argc, argv);
   MyThread th1;
   th1.run();

   return a.exec();
}
void func()
{ 
   cout << "This string from thread!"<<endl;
}

On the second string of the code, I have an error. The compiler doesn't "see" , I know that i must "include" 11 standard, so i go to .pro and paste CONFIG += c++11, but it isn't helping me :C Please, I need your help!

You try to use QThread subclass, but you said that you want to use C++11 thread so use this:

#include <thread>
#include <QDebug>
#include <QApplication>
#include <iostream>

void foo()
{
    std::cout << "This string from thread!"<<endl;
    //while(true)
    //{
    //    qDebug() <<"works";
    //    Sleep(500);
    //}
}

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    std::thread t(foo);
    t.join();
    return a.exec();
}

Also next is wrong:

   MyThread th1;
   th1.run();

Should be:

   MyThread th1;
   th1.start();

Details about threading with Qt classes:

http://blog.qt.digia.com/blog/2010/06/17/youre-doing-it-wrong/

http://qt-project.org/doc/qt-5/thread-basics.html

http://qt-project.org/doc/qt-5/qtconcurrent-index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM