c++ - 你能通过保证多个线程不会访问同一个内存来避免锁定吗?

标签 c++ c multithreading lock-free

假设我有一个大数组,我想用多个线程处理内容。如果我将每个线程委托(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/

相关文章:

c++ - 返回左值的函数,总是返回左值引用

c - 返回指向结构指针数组的指针

c - while里面的"continue"是不是多余的?

c# - 与多个消费者一起使用 BlockingCollection

python - 当线程完成时触发事件

c++ - 为什么没有悬挂引用?

c++ - 当我已经对我的文件进行标记后,如何创建倒排索引?

c++ - 从字节缓冲区转换结构

c - 在 header 中声明枚举,在源文件中不可见?

c# - ASP.NET 多线程 Web 请求