C++在不同线程中改变向量
C++ changing vector in different thread
我试图在另一个线程中更改向量,但向量的值没有更改。我原以为使用std::ref
可以解决这个问题,但没有成功。
这是启动线程的代码:
printf("tmp size: %dn", tmp_size);
printf("before change");
printArray(tmp);
std::thread threads[1];
for(int i = 0; i < 1; i++){
threads[i] = std::thread(callback, std::ref(tmp));
}
for(int i = 0; i < 1; i++){
threads[i].join();
}
printf("after join: ");
printArray(tmp);
这是回调:
void callback(std::vector<uint64_t> tmp){
tmp[0] = 1;
printf("inside callback");
printArray(tmp);
}
输出为:
tmp size: 2 before change 0 0 inside callback 1 0 after join: 0 0
我原以为线程更改向量后,值将是:内部回调:1 0。它不是通过引用传递的吗?
您正在传递对函数的引用,但随后函数按值获取其参数,并为其提供引用的值。修改引用的值没有好处。您需要修改引用。以下是如何正确操作的演示:
#include <vector>
#include <stdint.h>
#include <thread>
void callback(std::vector<uint64_t> &tmp)
{
tmp[0] += 1;
}
int main()
{
std::thread threads[1];
std::vector<uint64_t> tmp;
tmp.push_back(1);
for(int i = 0; i < 1; i++)
threads[i] = std::thread(callback, std::ref(tmp));
for(int i = 0; i < 1; i++)
threads[i].join();
printf("%dn", (int) tmp[0]);
}
如果希望回调更改向量,则必须通过指针或引用传递。
您的回调代码已经复制了它。
另一个有时更安全线程的选项是,将向量"移动"到线程中,然后在线程结束时将其移回。像这样:
#include <thread>
#include <future>
#include <vector>
#include <iostream>
std::vector<int> addtovec(std::vector<int> vec, int add) {
for(auto &x: vec) {
x += add;
}
return vec;
}
std::ostream& operator<<(std::ostream& os, const std::vector<int> &v) {
os << '{';
bool comma = false;
for(const auto &x: v) {
if(comma) os << ',';
comma = true;
os << x;
}
os << '}';
return os;
}
int main() {
std::vector<int> a{1,2,3,9,8,7};
std::cout << "before: " << a << std::endl;
auto future = std::async(addtovec, std::move(a), 5);
std::cout << "after move: " << a << std::endl;
a = future.get();
std::cout << "after get: " << a << std::endl;
return 0;
}
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 变量没有改变?通过向量的函数调用
- C++在不同线程中改变向量
- 在向量内更改变量的值不会改变其在向量外的值
- C++去除前x个元素的有效方法,在不改变向量大小的情况下将第x+1个元素推到第一个
- 通过引用传递向量的值在传递的原始向量中不会改变
- 分配矩阵列标准偏差的向量正在改变其值(RcppArmadillo)
- 应该很琐碎,为什么我不能改变我的向量的值
- 一个元素不能改变的非守恒向量
- 为什么向量分配会改变分配的向量
- 提升::p tr_向量改变元素顺序
- 为什么std::sort()改变了排序向量
- 一些向量元素不会改变
- c++的共享指针向量.如果在vector外强制转换,它会改变vector中的指针吗?< / h1 >
- 使用swap vs改变指向向量的指针
- 将向量数组作为函数参数传递(值不会改变)
- 为什么我的向量中的字符串没有改变值?
- 在c++中,如何改变元素在一个向量中的位置,并对另一个不同的向量进行相同的改变