[英]C++ changing vector in different thread
我試圖在不同的線程中更改向量,但向量的值沒有改變。 我試圖尋找答案,我認為使用 std::ref 可以解決問題,但沒有用。
**編輯:更簡單的代碼
這是啟動線程的代碼:
printf("tmp size: %d\n", 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
我期待在線程更改向量后,值將是:inside callback: 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("%d\n", (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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.