mirror of
https://github.com/vlang/v.git
synced 2023-08-10 21:13:21 +03:00
sync: channel implementation (#6074)
This commit is contained in:
@ -26,11 +26,13 @@ struct RwMutexAttr {
|
||||
|
||||
/* MacOSX has no unnamed semaphores and no `timed_wait()` at all
|
||||
so we emulate the behaviour with other devices */
|
||||
[ref_only]
|
||||
struct MacOSX_Semaphore {
|
||||
mtx C.pthread_mutex_t
|
||||
cond C.pthread_cond_t
|
||||
attr C.pthread_condattr_t
|
||||
mut:
|
||||
count int
|
||||
count u32
|
||||
}
|
||||
|
||||
[ref_only]
|
||||
@ -38,19 +40,8 @@ struct PosixSemaphore {
|
||||
sem C.sem_t
|
||||
}
|
||||
|
||||
[ref_only]
|
||||
struct CondAttr {
|
||||
attr C.pthread_condattr_t
|
||||
}
|
||||
|
||||
pub struct Semaphore {
|
||||
/*
|
||||
$if macos {
|
||||
sem &MacOSX_Semaphore
|
||||
} $else {
|
||||
sem &PosixSemaphore
|
||||
}
|
||||
*/
|
||||
mut:
|
||||
sem voidptr // since the above does not work, yet
|
||||
}
|
||||
|
||||
@ -99,22 +90,26 @@ pub fn (mut m RwMutex) w_unlock() {
|
||||
C.pthread_rwlock_unlock(&m.mutex)
|
||||
}
|
||||
|
||||
[inline]
|
||||
pub fn new_semaphore() Semaphore {
|
||||
return new_semaphore_init(0)
|
||||
}
|
||||
|
||||
pub fn new_semaphore_init(n u32) Semaphore {
|
||||
$if macos {
|
||||
s := Semaphore{
|
||||
sem: &MacOSX_Semaphore{count: 0}
|
||||
sem: &MacOSX_Semaphore{count: n}
|
||||
}
|
||||
C.pthread_mutex_init(&&MacOSX_Semaphore(s.sem).mtx, C.NULL)
|
||||
a := &CondAttr{}
|
||||
C.pthread_condattr_init(&a.attr)
|
||||
C.pthread_condattr_setpshared(&a.attr, C.PTHREAD_PROCESS_PRIVATE)
|
||||
C.pthread_cond_init(&&MacOSX_Semaphore(s.sem).cond, &a.attr)
|
||||
C.pthread_condattr_init(&&MacOSX_Semaphore(s.sem).attr)
|
||||
C.pthread_condattr_setpshared(&&MacOSX_Semaphore(s.sem).attr, C.PTHREAD_PROCESS_PRIVATE)
|
||||
C.pthread_cond_init(&&MacOSX_Semaphore(s.sem).cond, &&MacOSX_Semaphore(s.sem).attr)
|
||||
return s
|
||||
} $else {
|
||||
s := Semaphore{
|
||||
sem: &PosixSemaphore{}
|
||||
}
|
||||
unsafe { C.sem_init(&&PosixSemaphore(s.sem).sem, 0, 0) }
|
||||
unsafe { C.sem_init(&&PosixSemaphore(s.sem).sem, 0, n) }
|
||||
return s
|
||||
}
|
||||
}
|
||||
@ -186,3 +181,13 @@ pub fn (s Semaphore) timed_wait(timeout time.Duration) bool {
|
||||
return unsafe { C.sem_timedwait(&&PosixSemaphore(s.sem).sem, &t_spec) == 0 }
|
||||
}
|
||||
}
|
||||
|
||||
pub fn (s Semaphore) destroy() bool {
|
||||
$if macos {
|
||||
return C.pthread_cond_destroy(&&MacOSX_Semaphore(s.sem).cond) == 0 &&
|
||||
C.pthread_condattr_destroy(&&MacOSX_Semaphore(s.sem).attr) == 0 &&
|
||||
C.pthread_mutex_destroy(&&MacOSX_Semaphore(s.sem).mtx) == 0
|
||||
} $else {
|
||||
return unsafe { C.sem_destroy(&&PosixSemaphore(s.sem).sem) == 0 }
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user