gpt4 book ai didi

c++ - 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?

转载 作者:行者123 更新时间:2023-11-28 01:19:46 25 4
gpt4 key购买 nike

假设我有以下高级格式的 C++ 代码:

#include <thread>
void func1(vector<double> &somevec1, vector<double> &somevec2, size_t somesize){

//somevec1 and somesize and a bunch of local variables being used to modify somevec2
//somevec1 and somevec2 and somesize are all the same across all threads, but each thread is working on a different part of somevec2

}

vector<double> mainfunc(vector<double> &passingvector){

//a bunch of stuff involving local variables

// A thread is made that uses func1
// Another thread is made that uses func1
//in fact the number of threads being made that uses func1 depends entirely on the size of "passing vector"

//a bunch of other stuff involving local variables

//return the vector
}

我是否必须担心所有这些线程共享 func1 函数中的数据,或者每个线程是否为这些 func1 局部变量拥有自己的堆栈空间?

如果我确实需要为此担心,那么我该如何解决这个问题呢?我对使用线程非常陌生。我是否必须使用互斥锁或信号量来处理这个问题?

我问这个的原因是因为我不断遇到段错误,我想弄清楚这是否是因为线程可能在 func1 中共享变量。我正在尝试使用 gdb,但我对它还很陌生,所以我很难理解发生了什么。有谁知道可以帮助我以更具可读性的方式识别段错误的方法吗?

谢谢:)

最佳答案

每个线程都有自己的堆栈,因此在它调用的函数中有自己独立的局部变量。

但是,您通过引用传递给函数的那些 vector 可以共享(如果您在不同线程中通过引用传递相同的 vector ),在这种情况下将需要同步。

关于c++ - 如果两个线程调用同一个函数,但函数中的所有变量都是局部变量,我还需要担心线程之间共享数据吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57033914/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com