Skip to content

Commit

Permalink
runtime: add the osyield function
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Dec 13, 2024
1 parent bf2fec4 commit 24cb047
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
18 changes: 18 additions & 0 deletions std/runtime/thread_unix.jule
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@
use integ "std/jule/integrated"

cpp use "<pthread.h>"
cpp use "<sched.h>"

cpp unsafe fn pthread_create(*cpp.pthread_t, *unsafe, *unsafe, *unsafe): int
cpp fn pthread_detach(cpp.pthread_t): int
cpp fn sched_yield(): int

#typedef
cpp struct pthread_t{}
Expand All @@ -19,4 +21,20 @@ unsafe fn _coSpawn(func: *unsafe, args: *unsafe): bool {
}
cpp.pthread_detach(t)
ret true
}

fn osyield() {
// Maximum attemp count to switch thread.
// This is the total number of attempts.
const AttempCount = 4
if cpp.sched_yield() == 0 {
ret
}
mut n := 1
for n < AttempCount; n++ {
if cpp.sched_yield() == 0 {
ret
}
}
panic("runtime: thread scheduling error")
}
17 changes: 17 additions & 0 deletions std/runtime/thread_windows.jule
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ use integ "std/jule/integrated"
use "std/sys"

cpp unsafe fn CreateThread(*unsafe, int, *unsafe, *unsafe, int, *unsafe): *unsafe
cpp fn SwitchToThread(): bool

unsafe fn _coSpawn(func: *unsafe, args: *unsafe): bool {
handle := cpp.CreateThread(nil, 0, integ::Emit[*unsafe]("(unsigned long(*)(void*))({})", func), args, 0, nil)
Expand All @@ -14,4 +15,20 @@ unsafe fn _coSpawn(func: *unsafe, args: *unsafe): bool {
}
sys::CloseHandle(sys::Handle(handle))
ret true
}

fn osyield() {
// Maximum attemp count to switch thread.
// This is the total number of attempts.
const AttempCount = 4
if cpp.SwitchToThread() {
ret
}
mut n := 1
for n < AttempCount; n++ {
if cpp.SwitchToThread() {
ret
}
}
panic("runtime: thread scheduling error")
}

0 comments on commit 24cb047

Please sign in to comment.