我有以下程序。我收到这个奇怪的运行时错误,对我来说没有意义。我正在与pthread连接。更多文字摆脱烦人的代码框。
#include <iostream>
#include <future>
#include <exception>
#include <stdexcept>
#include <thread>
#include <list>
class OneTask
{
std::promise<std::list<int> > resList;
public:
void Execute(int x)
{
std::list<int> res;
for(int i = 0; i < x; ++i)
{
res.push_back(i);
}
resList.set_value(move(res));
}
std::future<std::list<int> > Result()
{
return resList.get_future();
}
};
int main(int argc, char **argv)
{
std::cout << "start" << "\n";
OneTask ot;
std::cout << "before fut=" << "\n";
std::future<std::list<int> > fut = ot.Result();
std::cout << "before creation of th" << "\n";
std::thread th(&OneTask::Execute, &ot, 2);
std::cout << "before fut.get" << "\n";
std::list<int> res = fut.get();
int r = res.size();
std::cout << r << std::endl;
std::cout << "before join" << "\n";
th.join();
while(1)
;
return 0;
}
当我运行它时,我得到了这个:
idf@idf-Satellite-C55t-A ~/Documents/STDPromiseFuture/bin/Release $ ./STDPromiseFuture
start
before fut=
before creation of th
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted
idf@idf-Satellite-C55t-A ~/Documents/STDPromiseFuture/bin/Release $
这是编译的方式:
修改
g++ -Wall -pthread -O2 -std=c++11 -c /home/idf/Documents/STDPromiseFuture/STDPromiseFuture.cpp -o obj/Release/STDPromiseFuture.o
g++ -Wl,--no-as-needed -o bin/Release/STDPromiseFuture obj/Release/STDPromiseFuture.o -s -lpthread -lrt
Output file is bin/Release/STDPromiseFuture with size 18.53 KB
Process terminated with status 0 (0 minute(s), 2 second(s))
0 error(s), 0 warning(s) (0 minute(s), 2 second(s))
idf@idf-Satellite-C55t-A ~/Documents/STDPromiseFuture/bin/Release $ g++ --version
g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2
Copyright (C) 2013 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
idf@idf-Satellite-C55t-A ~/Documents/STDPromiseFuture/bin/Release $