假设我有一个大数组,我想用多个线程处理内容。如果我将每个线程委托(delegate)给一个特定的部分,保证没有重叠,那么假设线程不访问数组之外的任何其他内存,这是否消除了任何锁定需求?
类似这样的东西(伪代码):
global array[9000000];
do_something(chunk) {
for (i = chunk.start; i < chunk.end; i++)
//do something with array
}
main() {
chunk1 = {start: 0, end: 5000000};
chunk2 = {start: 5000000, end: 9000000};
start_thread(thread1, do_something(chunk1));
start_thread(thread2, do_something(chunk2));
wait_for_join(thread1);
wait_for_join(thread2);
//do something else with the altered array
}
最佳答案
在符合标准的 C++11 编译器中,这是安全的 [intro.memory] (§1.7):
A memory location is either an object of scalar type or a maximal sequence of adjacent bit-fields all having non-zero width. [...] Two threads of execution (1.10) can update and access separate memory locations without interfering with each other.
C11 在 §3.14 中给出了相同的保证(甚至使用相同的措辞)。
在 C++03 编译器中,标准不保证这可以正常工作,但如果编译器提供类似的保证作为扩展,它可能仍然有效。
关于c++ - 你能通过保证多个线程不会访问同一个内存来避免锁定吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20548528/