gpt4 book ai didi

c++ - 尝试从类中启动成员函数的线程

转载 作者:行者123 更新时间:2023-11-30 01:46:29 24 4
gpt4 key购买 nike

这是我的类(class)的简要概述:

class foo{
public:
vector<string> rawData;
vector<vector<string> > slicedData;
void readData();
void sortData();
private:
static void selectionSort(vector<string>);
};

基本上,readData 使用来自外部文件的信息填充 rawData。执行此操作后,sortData 会将数据拆分为子集,每个子​​集都存储在 slicedData 中。我需要生成一个 selectionSort 线程来对每个子集进行排序,我必须在 sortData 中这样做。

我在 sortData 中尝试过这种方式:

thread *threads = new thread[slicedData.size()];

for(int i = 0; i < slicedData.size(); i++){
threads[i] = thread(selectionSort,slicedData[i]);
}

...但是当我这样做时,g++ 抛出 error: attempt to use a deleted function

为了记录,我需要将线程存储在一个数组中,以便稍后加入它们。我意识到这可以通过 boost 库和线程组更优雅地完成,但我正在努力保持这个项目的无依赖性。

最佳答案

我无法重现您的错误,但可以为我编译以下代码。

我建议使用线程 vector 并调用emplace_back() vector ..

像这样:

class foo
{
public:
std::vector<std::vector<std::string> > slicedData;

void sortData()
{
std::vector<std::thread> threads;

// for each slice add a new thread passing the function and data
// to its constructor
for(auto& slice: slicedData)
threads.emplace_back(&foo::selectionSort, std::ref(slice));
// NOTE: use of std::ref() to pass by reference

// now join the threads to prevent the threads vector
// going out of scope before they finish
for(auto&& thread: threads)
thread.join();

}

private:
static void selectionSort(std::vector<std::string>&); // pass by reference
};

另请注意,我通过引用 传递数据,因为我怀疑您真的不想对数据拷贝进行排序。

关于c++ - 尝试从类中启动成员函数的线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33175781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com