From 74115fe70adc04aadc65215e5adb910592df0da4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Uwe=20Kr=C3=BCger?= <45282134+UweKrueger@users.noreply.github.com> Date: Sat, 23 Jan 2021 16:03:21 +0100 Subject: [PATCH] parser: auto-import `sync` when `shared` objects are used (#8294) --- vlib/v/parser/parser.v | 3 +++ vlib/v/tests/shared_autolock_test.v | 34 +++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 vlib/v/tests/shared_autolock_test.v diff --git a/vlib/v/parser/parser.v b/vlib/v/parser/parser.v index d889f401bf..a8c93cd484 100644 --- a/vlib/v/parser/parser.v +++ b/vlib/v/parser/parser.v @@ -1034,6 +1034,9 @@ pub fn (mut p Parser) parse_ident(language table.Language) ast.Ident { // p.warn('name ') is_shared := p.tok.kind == .key_shared is_atomic := p.tok.kind == .key_atomic + if is_shared { + p.register_auto_import('sync') + } mut_pos := p.tok.position() is_mut := p.tok.kind == .key_mut || is_shared || is_atomic if is_mut { diff --git a/vlib/v/tests/shared_autolock_test.v b/vlib/v/tests/shared_autolock_test.v new file mode 100644 index 0000000000..f898ab4a64 --- /dev/null +++ b/vlib/v/tests/shared_autolock_test.v @@ -0,0 +1,34 @@ +const iterations = 100000 + +fn inc_array_elem(shared b []int, i int) { + for _ in 0 .. iterations { + b[i]++ + } +} + +fn test_autolock_array() { + shared a := &[1, 2, 7, 5] + t := go inc_array_elem(shared a, 2) + for _ in 0 .. iterations { + a[2]++ + } + t.wait() + assert a[2] == 2 * iterations + 7 +} + +fn inc_map_elem(shared b map[string]int, k string) { + for _ in 0 .. iterations { + b[k]++ + } +} + +fn test_autolock_map() { + shared m := &{'xy': 1, 'qwe': 2, 'asd': 7, 'iop': 5} + t := go inc_map_elem(shared m, 'asd') + for _ in 0 .. iterations { + m['asd']++ + } + t.wait() + assert m['asd'] == 2 * iterations + 7 +} +