我真的需要互斥锁,在这种情况下? [英] Do I really need mutex lock in this case?

查看:122
本文介绍了我真的需要互斥锁,在这种情况下?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑我们有三个线程,布尔status_flag [500] 数组和工作情况如下:

Consider we have three thread, bool status_flag[500] array, and working situations as follow :


  1. 两个线程只能在 status_flag 数组中的不同的索引写。而第三个线程只读在任何索引。

  1. Two threads only writing in status_flag array at different index. while third thread is only reading at any index.

不同的指数在所有三个主题写作。虽然所有三个线程读取任何索引。

All three thread writing at different index. While all three threads reading at any index.

在写操作中,我们只是设置标志永远不会再重新设置。

In writing operation we are just setting the flag never reset it again.

status_flag [i] = true;

在读取操作,我们正在做这样的事情:

In reading operation we are doing something like that :

    for(;;){  //spinning to get flag true
       if(status_flag [i] == true){
           //do_something ;
           break;
       }
    }

如果编译器优化(分支prediction)code,会发生什么?

What happen if compiler optimize (branch prediction) code?

我看了很多关于锁,但仍然有混淆得出结论的结果。请帮我得出结论。

I have read lot about lock but still having confusion to conclude result. Please help me to conclude.

推荐答案

POSIX是很清楚这个

应用应确保通过控制一个以上的线程访问任何存储器位置(线程或进程)被限制,使得没有控制线程能够读取或修改的存储器位置,而控制的另一个线程可以修改它。

Applications shall ensure that access to any memory location by more than one thread of control (threads or processes) is restricted such that no thread of control can read or modify a memory location while another thread of control may be modifying it.

因此​​,没有锁定你不许读存储器,一些其他线程可能会写。此外,POSIX的那部分描述了功能将同步线程之间的存储器。前两个线程都要求任何在里面列出的功能,你不能保证一个线程所做的更改将是可见的其他线程。

So without locking you're not allowed to read memory that some other thread may be writing. Furthermore, that part of POSIX describes which function will synchronize the memory between the threads. Before both threads have called any of the functions listed in there, you have no guarantee that the changes made by one thread will be visible to the other thread.

这篇关于我真的需要互斥锁,在这种情况下?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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