C 中的多執行緒行程回傳張量,我想將它們按順序連接成一個張量。
在 C 中,我有一個回傳單個 1x8 張量的函式。
我同時多次呼叫此函式,std::thread并且我想將它回傳的張量連接成一個大張量。例如,我稱它為 12 次,我希望它完成后會有一個 12x8 的張量。
我需要將它們按順序連接起來,也就是說,用 0 呼叫的張量應該始終位于第 0 位,然后是第 1 位,依此類推。
我知道我可以讓函式回傳一個 12x8 張量,但我需要解決如何獲取多執行緒程序中產生的張量的問題。
在下面的嘗試中,我嘗試將張量連接到張量中all_episode_steps,但這會回傳錯誤。
如果您注釋掉該all_episode_steps行并將函式std::cout << one;放在get_tensorsreturn 陳述句上方,您會看到它似乎正在使用多執行緒來毫無問題地創建張量。
#include <torch/torch.h>
torch::Tensor get_tensors(int id) {
torch::Tensor one = torch::rand({8});
return one.unsqueeze(0);
}
torch::Tensor all_episode_steps;
int main() {
std::thread ths[100];
for (int id=0; id<12; id ) {
ths[id] = std::thread(get_tensors, id);
all_episode_steps = torch::cat({ths[id], all_episode_steps});
}
for (int id=0; id<12; id ) {
ths[id].join();
}
}
如果您想自己構建它,您可以在此處安裝 LibTorch。
下面是上面代碼的 CMakeLists.txt 檔案。
cmake_minimum_required(VERSION 3.0 FATAL_ERROR)
project(example-app)
find_package(Torch REQUIRED)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${TORCH_CXX_FLAGS}")
add_executable(example-app example-app.cpp)
target_link_libraries(example-app "${TORCH_LIBRARIES}")
set_property(TARGET example-app PROPERTY CXX_STANDARD 14)
# The following code block is suggested to be used on Windows.
# According to https://github.com/pytorch/pytorch/issues/25457,
# the DLLs need to be copied to avoid memory errors.
if (MSVC)
file(GLOB TORCH_DLLS "${TORCH_INSTALL_PREFIX}/lib/*.dll")
add_custom_command(TARGET example-app
POST_BUILD
COMMAND ${CMAKE_COMMAND} -E copy_if_different
${TORCH_DLLS}
$<TARGET_FILE_DIR:example-app>)
endif (MSVC)
uj5u.com熱心網友回復:
執行緒不能回傳張量,但可以通過指標修改張量。試試這個(未經測驗,可能需要一些調整):
void get_tensors(torch::Tensor* out) {
torch::Tensor one = torch::rand({8});
*out = one.unsqueeze(0);
}
int main() {
std::thread ths[12];
std::vector<torch::Tensor> results(12);
for (int id=0; id<12; id ) {
ths[id] = std::thread(get_tensors, &results[id]);
}
for (int id=0; id<12; id ) {
ths[id].join();
}
auto result2d = torch::cat(results);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/504215.html
上一篇:更改矢量時如何保持執行緒解開?C
