简体   繁体   English

两个或多个std :: threads如何在同一函数上运行?

[英]How do two or more std::threads operate on the same function?

I am developing a C++ program in which I am processing several pairs of data(arrays and matrices). 我正在开发一个C ++程序,其中正在处理几对数据(数组和矩阵)。 Due to time requirements, I need to process corresponding pairs in parallel and I am planning to use std::threads for that purpose. 由于时间的限制,我需要并行处理相应的对,因此我打算为此使用std :: threads。 Since they will be calling the same function, I need to make sure that they never mess with each others' operations. 由于它们将调用相同的函数,因此我需要确保它们不会干扰彼此的操作。

I would like to know whether each thread creates its own call stack and local function variables for the same function called by different threads are unique to the caller. 我想知道每个线程是否创建自己的调用堆栈,并且由不同线程调用的同一函数的局部函数变量对于调用者而言是唯一的。

Also, all the threads need to write to different parts of the same output array. 同样,所有线程都需要写入同一输出数组的不同部分。 Will it cause a problem even if they are not writing to the same portion of the array? 即使它们没有写入数组的同一部分,也会引起问题吗?

You're fine. 你没事。

Each thread has its own stack and when two threads write to or read from different memory locations, there are no race conditions. 每个线程都有自己的堆栈,并且当两个线程向不同的内存位置写入或读取时,没有竞争条件。

Potential pitfalls in your case would be: 在您的情况下,潜在的陷阱可能是:

  • Your function writes to global variables. 您的函数将写入全局变量。
  • Your function gets parameters by reference and mutates them. 您的函数通过引用获取参数并将其变异。
  • There are locations in your output array that are accessed by both threads. 输出数组中有两个线程都可以访问的位置。

As a side note, if parallelization is that simple, it can be interesting to take a look at OpenMP or stuff like that that makes that kind of parallelization fairly simple. 附带说明一下,如果并行化是如此简单,那么看看OpenMP或类似的东西就可以使这种并行化相当简单,这很有趣。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在两个不同的线程中操作原子结构? - How to operate atomic struct in two different threads? 如何创建一个模板化函数可以对任何具有字符串键的 std::map 进行操作? - How do I create a templated function can that operate on any std::map that has a string key? std :: thread c ++。 更多线程相同的数据 - std::thread c++. More threads same data 使用两个以上的arg推导std :: function - Deducing std::function with more than two args 真的不可能同时挂起两个std/posix线程吗? - Is it really impossible to suspend two std/posix threads at the same time? 一个功能可以在几个线程上运行吗? - Can one function operate on few threads? 如果两个线程调用同一个函数,但是函数中的所有变量都是本地变量,我是否还需要担心线程之间共享数据? - If two threads call the same function, but all the variables in the function are locals, do I still have to worry about sharing data between threads? 将对象传递给两个std :: threads - Passing an object to two std::threads 如何使用两个或更多键实现 hash function? - How do I implement a hash function with two keys or more? 如何确保执行相同功能的两个线程互斥 - How can I ensure two threads executing the same function to be mutually exclusive
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM