Qt中的C++线程连接

C++ thread connect in Qt

本文关键字:连接 线程 C++ 中的 Qt      更新时间:2023-10-16

我开始在Qt中学习C++11标准中的线程。我不能包括库,没有这样的目录。例如,我有以下简单的代码:

#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;
}

在代码的第二个字符串上,我有一个错误。编译器没有"看到",我知道我必须"包括"11标准,所以我转到.pro并粘贴CONFIG+=c++11,但这对我没有帮助:c求你了,我需要你的帮助!

您尝试使用QThread子类,但您说过要使用C++11 thread,所以请使用以下内容:

#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();
}

下一个也是错误的:

   MyThread th1;
   th1.run();

应为:

   MyThread th1;
   th1.start();

有关Qt类线程的详细信息:

https://www.qt.io/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