- Can this test ever fail on x86, x64, ARM?
-
If so, is it possible to make it fail (in some sort of setup) and without changing the test code itself?
func Test_WaitGroup_Simple(t *testing.T) { var condition bool var wg sync.WaitGroup wg.Add(1) go func() { condition = true wg.Done() }() wg.Wait() if !condition { t.Error("Condition is false. But expected was true.") } }
您可以使“不正确同步”的测试失败吗?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- doucan8246326 2017-08-28 10:33关注
I have changed abit your test to make comparsion between atomic module:
package main import ( "sync" // "sync/atomic" "fmt" ) func main() { var condition int32 var wg sync.WaitGroup wg.Add(1) go func() { condition = 101 //atomic.StoreInt32(&condition,101) wg.Done() }() wg.Wait() if condition != 101 { fmt.Println("Condition is false. But expected was true.") } else { fmt.Println("Ok.") } }
https://play.golang.org/p/8ewy2uMNNH
With go asm we can check what code will be produced
go tool compile -S t.go
Here is production of inline code from
atomic.StoreInt32(&condition,101)
0x001d 00029 (t.go:15) MOVL $101, AX 0x0022 00034 (t.go:15) MOVQ "".&condition+24(FP), CX 0x0027 00039 (t.go:15) XCHGL AX, (CX) 0x0029 00041 (t.go:16) MOVQ "".&wg+32(FP), AX 0x002e 00046 (t.go:16) MOVQ AX, (SP) 0x0032 00050 (t.go:16) PCDATA $0, $1 0x0032 00050 (t.go:16) CALL sync.(*WaitGroup).Done(SB)
Here is production of
condition = 101
0x001d 00029 (t.go:14) MOVQ "".&condition+24(FP), AX 0x0022 00034 (t.go:14) MOVL $101, (AX) 0x0028 00040 (t.go:16) MOVQ "".&wg+32(FP), AX 0x002d 00045 (t.go:16) MOVQ AX, (SP) 0x0031 00049 (t.go:16) PCDATA $0, $1 0x0031 00049 (t.go:16) CALL sync.(*WaitGroup).Done(SB)
As You see there is not so much difference on the code. I have used int32 just to make the clean the difference for both cases. but go produces , more or less the same code for other atomic types including bool
If You look at the implementation of atomic/store function on i386 platform it acttually do nothing:
sync/atomic/asm_amd64.s
TEXT ·StoreUint32(SB),NOSPLIT,$0-8 MOVL addr+0(FP), BP MOVL val+4(FP), AX XCHGL AX, 0(BP) RET
But store 64 bit on 32 platform is already tricky and of course can not be replaced with simple "=" operation.
Thats why my answer is: This test will always pass on atleast 386 and amd64 platforms. The other thing that it is a bad practice - but it is actually the story from the other ticket.
解决 无用评论 打赏 举报
悬赏问题
- ¥50 用易语言http 访问不了网页
- ¥50 safari浏览器fetch提交数据后数据丢失问题
- ¥15 matlab不知道怎么改,求解答!!
- ¥15 永磁直线电机的电流环pi调不出来
- ¥15 用stata实现聚类的代码
- ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
- ¥20 docker里部署springboot项目,访问不到扬声器
- ¥15 netty整合springboot之后自动重连失效
- ¥15 悬赏!微信开发者工具报错,求帮改
- ¥20 wireshark抓不到vlan