我编写了一个小型C++程序,试图了解多线程如何使用std::thread
工作。这里是我的程序执行的步骤:多线程无法正常使用std :: thread(C++ 11)
- 初始化一个5×5整数矩阵,其中包含'Toto'类(初始化为主)中包含的唯一值'42'。
- 我打印初始化的5x5矩阵。
- 声明:
std::vector
共5线程。 - 我附加所有线程分别与他们的任务(
threadTask
方法)。每个线程将操纵一个std::vector<int>
实例。 - 我加入所有主题。
- 我打印了我的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]
,输出是c orrect。我认为我无法在main中打印正确的数据,因为printData()调用位于主线程中,并且threadTask
函数中的显示是正确的,因为该方法在其自己的线程(不是主线程)中执行。奇怪的是,这意味着在父进程中创建的所有线程都不能修改此父进程中的数据?我想我在代码中忘记了一些东西。我真的迷失了。有人可以帮我吗? 提前感谢您的帮助。
您需要了解C++值和引用语义。 'std :: vector vec = toto.getData()[i];'制作矢量的一个副本,所以原始文件永远不会被改变。该副本也会被复制到线程对象中,并且再也不会影响原始对象。 –
我使用getDataByRange新函数更新了我的问题,该函数根据范围返回对特定子向量的引用。所以我不会返回一个副本,而是一个参考。输出与修改后的输出相同。 – user1364743
问题不在于getData函数,它是与std :: vector vec = ...部分。这将调用vecs拷贝构造函数,vec将是getData返回的不同对象。 作为一个方面说明。考虑使用矢量构造函数在类构造函数中初始化矢量。 Toto():m_data(5,std :: vector (5,42)){ } 在我看来是一个更清洁的实现。 –