【问题标题】:How to use pthread on Qt Creator如何在 Qt Creator 上使用 pthread
【发布时间】:2012-07-27 11:21:20
【问题描述】:

我想执行下面的代码。

#include <iostream>
#include <thread>

void output() {
    std::cout << "Hello World" << std::endl;
}

int main()
{
    std::thread t(output);
    t.join();

    return 0;
}

我无法执行它。

Qt Creator 输出 在抛出 'std::system_error' 的实例后调用终止 what(): 不允许操作

但是我可以使用 -pthread 选项在终端上执行。 您能告诉我如何在 Qt Creator 中使用 -pthread 选项吗?

我的开发环境是Ubuntu(12.04)、g++4.6.3、Qt Creator(2.4.1)。

谢谢。

【问题讨论】:

    标签: c++ qt c++11 qt-creator


    【解决方案1】:

    在此处添加您的命令行参数: http://doc.qt.nokia.com/qtcreator-2.4/creator-run-settings.html

    【讨论】:

    • 谢谢。我可以在这里添加构建选项吗?
    【解决方案2】:

    这对我有用:

    TEMPLATE = app
    TARGET = 
    DEPENDPATH += .
    INCLUDEPATH += .
    
    # Input
    SOURCES += test.cpp
    
    QMAKE_CXXFLAGS += -std=gnu++0x -pthread
    QMAKE_CFLAGS += -std=gnu++0x -pthread
    

    您的示例在我的系统上使用上述 .pro 文件正确编译和执行。

    尝试将您的示例保存为 test.cpp,并将上述示例保存为 project.pro 在同一目录中。然后输入:

    $ qmake
    $ make
    $ ./project
    Hello World
    

    【讨论】:

    • 感谢您的回复。但是,它不起作用。在抛出“std::system_error”what() 实例后调用 Qt Creator 输出终止:不允许操作。
    • 对不起,我打错了。再试一次。
    • 谢谢。不幸的是,它也不起作用。我通过在终端上键入“g++ test.cpp -std=c++0x -pthread”或“g++ test.cpp -std=gnu0x -pthread”来确认执行。有什么问题?谢谢。
    • 使用上面的新 .pro 文件重试。并将 make 的输出粘贴到您的答案中。
    • 谢谢。我已经尝试过了,但它不起作用。在抛出 'std::system_error' what(): 的实例后调用 Qt Creator 输出终止。但是,在调试模式下,它可以工作。这是什么意思?
    【解决方案3】:

    您还需要链接到-pthread。如果您使用g++ main.cpp -std=c++0x -pthread,您可以一步完成所有操作,因此它可以正常工作。要让 Qt 做正确的事情,请将以下内容添加到您的项目文件中:

    QMAKE_CXXFLAGS += -std=c++0x -pthread 
    LIBS += -pthread
    

    【讨论】:

    • 谢谢,但它不起作用。在抛出 'std::system_error' what(): 的实例后调用 Qt Creator 输出终止。但是,在调试中,它正在工作。这是什么意思?
    • @hizz 你在更改 .pro 文件后重建了你的项目吗?
    • 哦,重建项目后它正在工作。从现在开始我会小心的。
    • 谢谢,它对我有用。唯一需要的是最后一条语句。
    • @bamboon 我已经包含了 pthread,为什么我还需要设置 LIBS,这真的让我很困惑。
    猜你喜欢
    • 1970-01-01
    • 2011-10-03
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2016-11-15
    • 1970-01-01
    相关资源
    最近更新 更多