From a932b46a8f4aa027046f0a54860320bb94577d8f Mon Sep 17 00:00:00 2001 From: mertcandav Date: Fri, 6 Dec 2024 18:27:58 +0300 Subject: [PATCH] std/sync: add test for Once --- std/runtime/lock.jule | 8 ++++---- std/sync/once_test.jule | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 43 insertions(+), 4 deletions(-) create mode 100644 std/sync/once_test.jule diff --git a/std/runtime/lock.jule b/std/runtime/lock.jule index 3a36d1c82..da420db24 100644 --- a/std/runtime/lock.jule +++ b/std/runtime/lock.jule @@ -65,7 +65,7 @@ const mutexWaiterShift = 3 const starvationThresholdNs = 1_100_000 // Advanced mutex implementation for common and public use. -// See the sync::Mutex for documentation. +// See the [sync::Mutex] for documentation. // This implementation derived from the original Go code, // but it may work different paritially. // For the original Go code, see the sync.Mutex of the Go stdlib. @@ -76,7 +76,7 @@ struct mutex { impl mutex { // Locks the mutex. - // See the [sync::Mutex.Lock] for documentation. + // See the [sync::Mutex] for documentation. fn lock(self) { // Fast path: grab unlocked mutex. if atomicCompareAndSwap(self.state, 0, mutexLocked, atomicSeqCst) { @@ -170,7 +170,7 @@ impl mutex { } // Tries to lock the mutex. - // See the [sync::Mutex.TryLock] for documentation. + // See the [sync::Mutex] for documentation. fn tryLock(self): bool { old := self.state if old&(mutexLocked|mutexStarving) != 0 { @@ -184,7 +184,7 @@ impl mutex { } // Unlocks the mutex. - // See the [sync::Mutex.Unlock] for documentation. + // See the [sync::Mutex] for documentation. fn unlock(self) { // Fast path: drop lock bit. new := atomicAdd(self.state, -mutexLocked, atomicSeqCst) diff --git a/std/sync/once_test.jule b/std/sync/once_test.jule new file mode 100644 index 000000000..4146ea619 --- /dev/null +++ b/std/sync/once_test.jule @@ -0,0 +1,39 @@ +// Copyright 2024 The Jule Programming Language. +// Use of this source code is governed by a BSD 3-Clause +// license that can be found in the LICENSE file. + +use "std/sync/atomic" +use "std/testing" + +type one: int + +impl one { + fn Increment(mut self) { + self++ + } +} + +fn run(t: &testing::T, once: &Once, mut o: &one, mut c: &int) { + once.Do(fn() { o.Increment() }) + if *o != 1 { + t.Errorf("once failed inside run: {} is not 1", *o) + } + atomic::Add(*c, 1, atomic::SeqCst) +} + +#test +fn testOnce(t: &testing::T) { + mut o := new(one) + mut once := new(Once) + mut c := new(int) + const N = 10 + mut i := 0 + for i < N; i++ { + co run(t, once, o, c) + } + for atomic::Load(*c, atomic::SeqCst) != N { + } + if *o != 1 { + t.Errorf("once failed outside run: {} is not 1", *o) + } +} \ No newline at end of file