6

我无法让 scons 正确编译一个小线程示例(在 Linux 上)。

如果我运行 scons,它会这样做:

jarrett@jarrett-laptop:~/projects/c++_threads$ scons
scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
g++ -o build/main.o -c -std=c++11 -pthread -Wall -g src/main.cpp
g++ -o build/c++threads build/main.o
scons: done building targets.

然后如果我运行./build/c++threads它会抛出这个错误:

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

如果我用这个从命令行编译:

g++ -std=c++11 -pthread -Wall -g src/main.cpp

它编译为a.out,如果我运行a.out它,它将运行程序(为线程做一些输出等)。

这是我的 SConstruct 文件:

# Tell SCons to create our build files in the 'build' directory
VariantDir('build', 'src', duplicate=0)

# Set our source files
source_files = Glob('build/*.cpp', 'build/*.h')

# Set our required libraries
libraries = []
library_paths = ''

env = Environment()

# Set our g++ compiler flags
env.Append( CPPFLAGS=['-std=c++11', '-pthread', '-Wall', '-g'] )

# Tell SCons the program to build
env.Program('build/c++threads', source_files, LIBS = libraries, LIBPATH = library_paths)

这是cpp文件:

#include <iostream>
#include <thread>
#include <vector>

//This function will be called from a thread

void func(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::vector<std::thread> th;

    int nr_threads = 10;

    //Launch a group of threads
    for (int i = 0; i < nr_threads; ++i) {
        th.push_back(std::thread(func,i));
    }

    //Join the threads with the main thread
    for(auto &t : th){
        t.join();
    }

    return 0;
}

任何人都知道我做错了什么???

感谢任何帮助!

干杯

贾勒特

4

1 回答 1

6

感谢@Joachim 和@bamboon 的评论。将 pthread 添加到链接器(scons 库)标志有效。

新的 scons 文件现在是:

# Tell SCons to create our build files in the 'build' directory
VariantDir('build', 'src', duplicate=0)

# Set our source files
source_files = Glob('build/*.cpp', 'build/*.h')

# Set our required libraries
libraries = ['pthread']
library_paths = ''

env = Environment()

# Set our g++ compiler flags
env.Append( CPPFLAGS=['-std=c++11', '-pthread', '-Wall', '-g'] )

# Tell SCons the program to build
env.Program('build/c++threads', source_files, LIBS = libraries, LIBPATH = library_paths)

再次感谢!

于 2012-10-15T18:28:01.120 回答