v/vlib/sync/sync_windows.c.v

86 lines
1.9 KiB
V
Raw Normal View History

2020-01-23 21:04:46 +01:00
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
2019-06-23 04:21:30 +02:00
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
2019-06-22 21:53:22 +02:00
module sync
2019-07-24 17:36:20 +02:00
// Mutex HANDLE
type MHANDLE voidptr
2019-06-22 21:53:22 +02:00
2019-10-25 16:24:40 +02:00
//[init_with=new_mutex] // TODO: implement support for this struct attribute, and disallow Mutex{} from outside the sync.new_mutex() function.
pub struct Mutex {
2019-07-24 17:36:20 +02:00
mut:
mx MHANDLE // mutex handle
state MutexState // mutex state
cycle_wait i64 // waiting cycles (implemented only with atomic)
cycle_woken i64 // woken cycles ^
reader_sem u32 // reader semarphone
writer_sem u32 // writer semaphones
2019-06-22 21:53:22 +02:00
}
enum MutexState {
broken
waiting
released
abandoned
destroyed
}
2019-06-22 21:53:22 +02:00
pub fn new_mutex() &Mutex {
sm := &Mutex{}
2019-10-25 16:24:40 +02:00
unsafe {
2020-04-02 20:58:07 +02:00
mut m := sm
2019-10-25 16:24:40 +02:00
m.mx = C.CreateMutex(0, false, 0)
if isnil(m.mx) {
m.state = .broken // handle broken and mutex state are broken
return sm
2020-04-02 20:58:07 +02:00
}
2019-10-25 16:24:40 +02:00
}
return sm
2019-10-25 16:24:40 +02:00
}
2019-07-24 17:36:20 +02:00
pub fn (m mut Mutex) lock() {
// if mutex handle not initalized
if isnil(m.mx) {
m.mx = C.CreateMutex(0, false, 0)
if isnil(m.mx) {
m.state = .broken // handle broken and mutex state are broken
return
}
}
2020-04-02 20:58:07 +02:00
state := C.WaitForSingleObject(m.mx, C.INFINITE) // infinite wait
2019-10-30 15:29:05 +01:00
/* TODO fix match/enum combo
m.state = match state {
2020-04-02 20:58:07 +02:00
C.WAIT_ABANDONED { .abandoned }
C.WAIT_OBJECT_0 { .waiting }
2019-10-30 14:43:40 +01:00
else { .broken }
}
2019-10-30 15:29:05 +01:00
*/
2020-04-02 20:58:07 +02:00
if state == C.WAIT_ABANDONED {
m.state = .abandoned
// FIXME Use C constant instead
} else if state == 0 /* C.WAIT_OBJECT_0 */ {
m.state = .waiting
} else {
m.state = .broken
}
2019-06-22 21:53:22 +02:00
}
2019-07-24 17:36:20 +02:00
pub fn (m mut Mutex) unlock() {
if m.state == .waiting {
2020-04-02 20:58:07 +02:00
if C.ReleaseMutex(m.mx) {
m.state = .broken
return
}
}
m.state = .released
}
2019-07-24 17:36:20 +02:00
pub fn (m mut Mutex) destroy() {
if m.state == .waiting {
m.unlock() // unlock mutex before destroying
}
C.CloseHandle(m.mx) // destroy mutex
m.state = .destroyed // setting up reference to invalid state
}