【问题标题】:Multi-threading does not work correctly using std::thread (C++ 11)使用 std::thread (C++ 11) 多线程无法正常工作
【发布时间】:2013-07-02 16:53:30
【问题描述】:

我编写了一个小型 c++ 程序来尝试了解使用 std::thread 的多线程是如何工作的。这是我的程序执行步骤:

  1. 初始化 5x5 整数矩阵,包含在“Toto”类中的唯一值“42”(在 main 中初始化)。
  2. 我打印初始化的 5x5 矩阵。
  3. 5 个线程的 std::vector 声明。
  4. 我将所有线程分别附加到它们的任务中(threadTask 方法)。每个线程都会操作一个std::vector<int> 实例。
  5. 我加入所有线程。
  6. 我打印 5x5 矩阵的新状态。

这是输出:

42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42

42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42

应该是:

42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42
42 42 42 42 42

0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4

这是代码示例:

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

class       Toto
{
public:
    /*
    ** Initialize a 5x5 matrix with the 42 value.
    */
    void    initData(void)
    {
        for (int y = 0; y < 5; y++) {
            std::vector<int> vec;

            for (int x = 0; x < 5; x++) {
                vec.push_back(42);
            }
            this->m_data.push_back(vec);
        }
    }

    /*
    ** Display the whole matrix.
    */
    void    printData(void) const
    {
        for (int y = 0; y < 5; y++) {
            for (int x = 0; x < 5; x++) {
                printf("%d ", this->m_data[y][x]);
            }
            printf("\n");
        }
        printf("\n");
    }

    /*
    ** Function attached to the thread (thread task).
    ** Replace the original '42' value by the another one.
    */
    void    threadTask(std::vector<int> &list, int value)
    {
        for (int x = 0; x < 5; x++) {
            list[x] = value;
        }
    }

    /*
    ** Return a sub vector reference according to the range.
    */

    std::vector<int>    &getDataByRange(int range)
    {
        return (this->m_data[range]);
    }

    private:
        std::vector<std::vector<int> > m_data;
};

int         main(void)
{
    Toto    toto;

    toto.initData();

    toto.printData(); //Display the original 5x5 matrix (first display).

    std::vector<std::thread> threadList(5); //Initialization of vector of 5 threads.

    for (int i = 0; i < 5; i++) {  //Threads initializationss

        std::vector<int> &vec = toto.getDataByRange(i); //Get each sub-vectors reference.
        threadList.at(i) = std::thread(&Toto::threadTask, toto, vec, i); //Each thread will be attached to a specific vector.
    }

    for (int j = 0; j < 5; j++) {
        threadList.at(j).join();
    }

    toto.printData(); //Second display.
    getchar();

    return (0);
}

但是,在threadTask 方法中,如果我打印变量list[x],则输出是正确的。我想我无法在主线程中打印正确的数据,因为 printData() 调用在主线程中,而threadTask 函数中的显示是正确的,因为该方法是在自己的线程中执行的(不是主线程) .奇怪,就是说在一个父进程中创建的所有线程都不能修改这个父进程中的数据?我想我忘记了代码中的某些内容。我真的迷路了。有人可以帮助我吗? 非常感谢您的帮助。

【问题讨论】:

  • 您需要了解 C++ 值和引用语义。 std::vector&lt;int&gt; vec = toto.getData()[i]; 复制向量,因此原始向量永远不会被更改。然后该副本也被复制到线程对象中,并且永远不会影响原始对象。
  • 我使用 getDataByRange 新函数更新了我的问题,该函数根据范围返回对特定子向量的引用。所以我不返回副本而是参考。输出和我修改后的一样。
  • 问题不在于 getData 函数,而在于 std::vector vec = ... 部分。这将调用 vecs 复制构造函数,并且 vec 将是与 getData 返回的对象不同的对象。作为旁注。考虑使用向量构造函数在类构造函数中初始化向量。 Toto() : m_data(5, std::vector(5, 42) ) { } 在我看来是一个更简洁的实现。
  • 主题已更新。我使用 getDataByRange 新方法,它根据其范围返回一个向量的引用 (std::vector &vec = toto.getDataByRange(i))。

标签: c++ multithreading c++11 stdthread


【解决方案1】:

在我看来,您在撰写本文时所做的许多选择都使您的工作变得比必要的困难得多。特别是,您的 toto 类似乎(对我而言)使客户端代码更复杂而不是更简单,并且无法封装它操作的数据。我想如果我要这样做,我会按照以下一般思路编写更多代码:

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

std::ostream &operator<<(std::ostream &os, std::vector<int> const &d) {
    for (auto const &v : d)
        os << v << "\t";
    return os;
}

std::ostream &operator<<(std::ostream &os, std::vector <std::vector<int>> const &d) {
    for (auto const &v : d)
        os << v << "\n";
    return os;
}

int main(void) {
    std::vector<std::vector<int>> d(5, std::vector<int>(5, 42));

    std::cout << d;

    std::vector<std::thread> threads;

    for (int i = 0; i < 5; i++)
        threads.emplace_back([i, &d]() {std::fill(d[i].begin(), d[i].end(), i); });

    std::for_each(threads.begin(), threads.end(), [](std::thread &t){t.join(); });

    std::cout << "\n" << d;
}

【讨论】:

    【解决方案2】:

    我解决了我的问题。一切都来自于这条线:

    threadList.at(i) = std::thread(&Toto::threadTask, toto, **vec**, i);
    

    必须是:

    threadList.at(i) = std::thread(&Toto::threadTask, toto, **&vec**, i);
    

    我的函数'threadTask'必须在第一个参数中接受一个指针(不是引用)。

    void    threadTask(std::vector<int> *list, int value)
        {
            printf("b=%p\n", list);
            getchar();
            for (int x = 0; x < 5; x++) {
                (*list)[x] = value;
            }
        }
    

    我希望这个例子对某人有所帮助。

    【讨论】:

    • 或者,您可以像第一次尝试一样使用参考。但是,您可以使用 std::ref 作为参数调用 std::thread,如下所示:std::thread(&amp;Toto::threadTask, toto, std::ref(vec), i);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多