您可以通过确保多个线程不会访问同一内存来避免锁定吗? [英] Can you avoid locking by guaranteeing that multiple threads won't access the same memory?

查看:62
本文介绍了您可以通过确保多个线程不会访问同一内存来避免锁定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个大数组,我想用多个线程处理内容.如果我将每个线程都委派到特定的部分,以确保不存在重叠,那么假设线程不访问数组外部的任何其他内存,这是否消除了锁定的需要?

Say I have a large array and I want to process the contents with multiple threads. If I delegate each thread to a specific section, guaranteeing no overlap, does that eliminate any need for locking, assuming the threads don't access any other memory outside the array?

类似这样的东西(伪代码):

Something like this (pseudo-code):

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):

In a conforming C++11 compiler this is safe [intro.memory] (§1.7):

内存位置是标量类型的对象或最大的对象 全部具有非零宽度的相邻位域的序列. [...] 二 执行线程(1.10)可以更新和访问单独的内存 位置而不会互相干扰.

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节中提供相同的保证(甚至使用相同的措词).

C11 gives identical guarantees (they even use the same wording) in §3.14.

在C ++ 03编译器中,不能保证此标准可以工作,但是如果编译器提供与扩展类似的保证,它可能仍然可以工作.

In a C++03 compiler this is not guaranteed to work by the standard, but it might still work if the compiler provides similar guarantees as an extension.

这篇关于您可以通过确保多个线程不会访问同一内存来避免锁定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆