Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pthread on Qt Creator

I want to execute a following code.

#include <iostream>
#include <thread>

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

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

    return 0;
}

I can't execute it.

Qt Creator outputs terminate called after throwing an instance of 'std::system_error' what(): Operation not permitted

However I can execute on the terminal using the option of -pthread. Could you tell me how to use the option of -pthread in Qt Creator?

My developing environment is Ubuntu(12.04), g++4.6.3, Qt Creator(2.4.1).

Thank you.

like image 566
hizz Avatar asked Jul 29 '12 15:07

hizz


People also ask

How do I add Pthread library to QT?

According to randombit: "Botan uses threads internally, you may have to add -pthread to gcc command line." I think you can add this by QMAKE_CXXFLAGS += -pthread ( QMAKE_CLFLAGS for C files resp.) to your . pro file.

How does Pthread create work?

The pthread_create() function is used to create a new thread, with attributes specified by attr, within a process. If attr is NULL, the default attributes are used. If the attributes specified by attr are modified later, the thread's attributes are not affected.

How do you define Pthread?

POSIX Threads, commonly known as pthreads, is an execution model that exists independently from a language, as well as a parallel execution model. It allows a program to control multiple different flows of work that overlap in time.


2 Answers

You also need to link against -pthread. If you use g++ main.cpp -std=c++0x -pthread you are doing all that in one step, so it works correctly. To make Qt do the correct things, add the following to your project file:

QMAKE_CXXFLAGS += -std=c++0x -pthread 
LIBS += -pthread
like image 150
Stephan Dollberg Avatar answered Sep 29 '22 15:09

Stephan Dollberg


This works for me:

TEMPLATE = app
TARGET = 
DEPENDPATH += .
INCLUDEPATH += .

# Input
SOURCES += test.cpp

QMAKE_CXXFLAGS += -std=gnu++0x -pthread
QMAKE_CFLAGS += -std=gnu++0x -pthread

Your example compiles and executes correctly with the above .pro file on my system.

Try save your example as test.cpp, and the above as project.pro in same directory. Then type:

$ qmake
$ make
$ ./project
Hello World
like image 39
Andrew Tomazos Avatar answered Sep 29 '22 14:09

Andrew Tomazos