C++ 11 std::thread 奇怪的行为

2024-04-06

我正在尝试使用 std::thread 和 C++11,并且遇到了奇怪的行为。 请看一下下面的代码:

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

void thread_sum_up(const size_t n, size_t& count) {
  size_t i;
  for (i = 0; i < n; ++i);
  count = i;
}

class A {
public:
  A(const size_t x) : x_(x) {}

  size_t sum_up(const size_t num_threads) const {
    size_t i;
    std::vector<std::thread> threads;
    std::vector<size_t> data_vector;
    for (i = 0; i < num_threads; ++i) {
      data_vector.push_back(0);
      threads.push_back(std::thread(thread_sum_up, x_, std::ref(data_vector[i])));
    }

    std::cout << "Threads started ...\n"; 

    for (i = 0; i < num_threads; ++i)
      threads[i].join();

    size_t sum = 0;
    for (i = 0; i < num_threads; ++i)
      sum += data_vector[i];
    return sum;
  }

private:
  const size_t x_;
};

int main(int argc, char* argv[]) {
  const size_t x = atoi(argv[1]);
  const size_t num_threads = atoi(argv[2]);
  A a(x);
  std::cout << a.sum_up(num_threads) << std::endl;
  return 0;
}

这里的主要思想是,我想指定一些执行独立计算的线程(在本例中是简单的增量)。 所有线程完成后,应合并结果以获得总体结果。

只是澄清一下:这仅用于测试目的,以便让我了解如何 C++11 线程工作。

但是,当使用命令编译此代码时

g++ -o threads threads.cpp -pthread -O0 -std=c++0x

在 Ubuntu 机器上,当我执行生成的二进制文件时,我会得到非常奇怪的行为。 例如:

$ ./threads 1000 4
Threads started ...
Segmentation fault (core dumped)

(应该产生输出:4000)

$ ./threads 100000 4
Threads started ...
200000

(应该产生输出:400000)

有人知道这里发生了什么事吗?

先感谢您!


你的代码有很多问题(甚至看到thread_sum_up大约 2-3 个错误)但我通过浏览代码发现的主要错误在这里:

data_vector.push_back(0);
threads.push_back(std::thread(thread_sum_up, x_, std::ref(data_vector[i])));

瞧,当你push_back变成一个向量(我说的是data_vector),它可以移动所有以前的数据记忆中的周围。但是然后您获取线程的单元格的地址(引用),然后再次推回(使之前的参考无效)

这会导致你崩溃。

为了轻松修复 - 添加data_vector.reserve(num_threads);就在创建之后。

Edit根据您的要求 - 中的一些错误thread_sum_up

void thread_sum_up(const size_t n, size_t& count) {
  size_t i;
  for (i = 0; i < n; ++i); // see that last ';' there? means this loop is empty. it shouldn't be there
  count = i; // You're just setting count to be i. why do that in a loop? Did you mean +=?
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 11 std::thread 奇怪的行为 的相关文章

随机推荐