在这种情况下我真的需要互斥锁吗?
Do I really need mutex lock in this case?
假设我们有三个线程,bool status_flag[500]
数组,工作情况如下:
两个线程仅在 不同索引 处写入 status_flag
数组。而第三个线程只读取任何索引。
所有三个线程都在不同的索引处写入。虽然所有三个线程都在读取任何索引。
在写入操作中,我们只是设置标志,不再重置它。
status_flag [i] = true;
在读取操作中,我们正在做类似的事情:
for(;;){ //spinning to get flag true
if(status_flag [i] == true){
//do_something ;
break;
}
}
如果编译器优化(分支预测)代码会怎样?
我已经阅读了很多关于锁的内容,但仍然对得出结论感到困惑。请帮我总结一下。
如果所有线程都对不同的索引值进行操作,那么就不需要锁。基本上相当于使用了不同的变量。
在您的代码中,变量 i 的值未设置或修改。所以它只读取特定的标志索引。对于写作,你使用不同的索引,在这种情况下不需要使用锁。
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 的那部分描述了哪个函数将同步线程之间的内存。在两个线程都调用其中列出的任何函数之前,您无法保证一个线程所做的更改对另一个线程可见。
假设我们有三个线程,bool status_flag[500]
数组,工作情况如下:
两个线程仅在 不同索引 处写入
status_flag
数组。而第三个线程只读取任何索引。所有三个线程都在不同的索引处写入。虽然所有三个线程都在读取任何索引。
在写入操作中,我们只是设置标志,不再重置它。
status_flag [i] = true;
在读取操作中,我们正在做类似的事情:
for(;;){ //spinning to get flag true
if(status_flag [i] == true){
//do_something ;
break;
}
}
如果编译器优化(分支预测)代码会怎样?
我已经阅读了很多关于锁的内容,但仍然对得出结论感到困惑。请帮我总结一下。
如果所有线程都对不同的索引值进行操作,那么就不需要锁。基本上相当于使用了不同的变量。 在您的代码中,变量 i 的值未设置或修改。所以它只读取特定的标志索引。对于写作,你使用不同的索引,在这种情况下不需要使用锁。
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 的那部分描述了哪个函数将同步线程之间的内存。在两个线程都调用其中列出的任何函数之前,您无法保证一个线程所做的更改对另一个线程可见。