gpt4 book ai didi

c++ - 如何修改线程中的字符串?

转载 作者:行者123 更新时间:2023-11-30 01:08:27 26 4
gpt4 key购买 nike

我正在尝试修改线程中的一些字符串(每个线程都有自己的字符串),但所有字符串都存储在一个 vector 中,因为我需要能够在线程完成它们的工作后访问它们。

我没有在 C++ 中使用线程,所以如果这是一件糟糕的事情,欢迎所有建议:)

基本上程序现在唯一要做的是:

  • 创建一些话题
  • 给每个线程发送一个字符串和一个id
  • 线程函数修改字符串以将id添加到它
  • 结束

这给出了一个段错误:(

这只是一个糟糕的方法吗?我还能怎么做?

static const int cores = 8;

void bmh_t(std::string & resr, int tid){
resr.append(std::to_string(tid));
resr.append(",");
return;
}

std::vector<std::string> parbmh(std::string text, std::string pat){

std::vector<std::string> distlists;
std::thread t[cores];
//Launch a group of threads
for (int i = 0; i < cores; ++i) {
distlists.push_back(" ");
t[i] = std::thread(bmh_t,std::ref(distlists[i]), i);
}

for (int i = 0; i < cores; ++i) {
t[i].join();
}

return distlists;
}

最佳答案

您的基本方法很好。编写并行代码时需要考虑的主要事情是线程之间共享的任何数据都以安全的方式完成。因为您的算法为每个线程使用不同的字符串,所以这是一个很好的方法。

您看到崩溃的原因是,在您已经为每个线程提供了对存储在 vector 中的数据的引用之后,您正在对字符串 vector 调用 push_back。这是一个问题,因为当 push_back 的大小达到其容量时,它需要增长您的 vector 。这种增长会使您分配给每个线程的引用失效,导致它们写入释放的内存。

修复非常简单:只需提前确保您的 vector 不需要增长即可。这可以通过指定初始元素数量的构造函数参数来完成;调用 reserve();或调用 resize()。

这是一个不会崩溃的实现:

static const int cores = 8;

void bmh_t(std::string & resr, int tid){
resr.append(std::to_string(tid));
resr.append(",");
return;
}

std::vector<std::string> parbmh(){

std::vector<std::string> distlists;
std::thread t[cores];
distlists.reserve(cores);

//Launch a group of threads
for (int i = 0; i < cores; ++i) {
distlists.push_back(" ");
t[i] = std::thread(bmh_t, std::ref(distlists[i]), i);
}

for (int i = 0; i < cores; ++i) {
t[i].join();
}

return distlists;
}

关于c++ - 如何修改线程中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42707337/

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