通过计数测试信号量 [英] Testing a semaphore by counting

查看:80
本文介绍了通过计数测试信号量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有关OS X上的信号量的文章.作者通过在两个线程中递增和递减静态变量来测试信号量.在信号量保护变量访问的情况下,变量最终为零.如果没有后卫,变量最终将具有虚假值.我尝试了代码,它可以工作.我不了解的是,来自两个线程的并发访问如何使最终变量值有所不同.毕竟,在我看来,一堆+1和–1应该是可交换的,对吗?我觉得我缺少明显的东西,那是什么? :)

There’s an article about semaphores on OS X. The author tests the semaphore by incrementing and decrementing a static variable in two threads. With semaphore guarding the variable access, the variable ends up being zero. Without the guard the variable ends up having some bogus value. I tried the code and it works. What I don’t understand is how may the concurrent access from the two threads make a difference in the final variable value. After all it seems to me like a bunch of +1s and –1s that should be comutative, right? I feel I am missing something glaring obvious, what is it? :)

推荐答案

问题是++/--不是原子的.它们本质上是三个操作:

The problem is that ++ / -- are not atomic. They are essentially three operations:

  1. 加载
  2. Inc/dec
  3. 商店

因此,如果两个线程同时加载值并同时存储它.差异将是1而不是2.

So if two threads load value simultaneously and store it also simultaneously. Difference will be 1 instead of 2.

这里是样品

Thread A Thread B
Load 5   Load 5
Inc 6    Inc 6
Store 6  Store 6

这篇关于通过计数测试信号量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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