mercredi 30 décembre 2015

Enable multithreading Eclipse C++

I have been trying to get a program working in Eclipse C++. One of the functions uses multithreading from std. Here is the function in the code:

void PrimeCheck::checkFull(long long int number)
{
    std::thread t1(&PrimeCheck::checkFirstHalf, this, number);
    std::thread t2(&PrimeCheck::checkSecondHalf, this, number);

    t1.join();
    t2.join();
}

When searching for a solution, I came across many solutions, all of which stating to either add a -pthread flag or a -std=c++11 in addition to changing the dialect to C++11. All of which I have done. This is what the compile command looks like in eclipse so you can see exactly which modifications I have already added:

Building file: ../src/Prime Checker.cpp
Invoking: GCC C++ Compiler
g++ -std=c++0x -D__GXX_EXPERIMENTAL_CXX0X__ -O2 -g -Wall -c -fmessage-length=0 -std=c++11  -pthread -Wl,--whole-archive -lpthread -Wl,--no-whole-archive -MMD -MP -MF"src/Prime Checker.d" -MT"src/Prime\ Checker.d" -o "src/Prime Checker.o" "../src/Prime Checker.cpp"
Finished building: ../src/Prime Checker.cpp

And this is the linker command as it appears in eclipse:

Invoking: GCC C++ Linker
g++ -Wl,--no-as-needed -pthread -shared -o [A bunch of .o files]

The code compiles correctly, and eclipse content assist recognizes thread as a member of std. Yet, when I run the program I still this error:

terminate called after throwing an instance of 'std::system_error'
  what():  Enable multithreading to use std::thread: Operation not permitted

To test this, I wrote a simple program outside of Eclipse which looked like this:

#include <thread>
#include <iostream>

using namespace std;

void func1(int x){
    for(int i=0; i<x; i++){
        cout << " " << 1 + i;
    }
}

void func2(){
    for(int j=0; j<5; j++){
        cout << "Standard message! ";
    }
}

int main(){
    int input;
    cout << "Give me a number:" << endl;
    cin >> input;

    thread t1(func1, input);
    thread t2(func2);
    t1.join();
    t2.join();


    return 0;
}

And compiled it in the terminal with this:

g++ ThreadTest.cpp -o Program.o -std=c++11 -pthread

And the program ran without error. I think this means that there's something wrong with Eclipse, but I'm not sure.

As a note, I'm doing this on Ubuntu 14.04 with gcc version 4.8.4. Also, I know that similar questions have been asked, but as far as I can tell, I've implemented those solutions with little success.

Help would be appreciated. Thanks!

Aucun commentaire:

Enregistrer un commentaire