1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
14 pub struct RWLock { inner: UnsafeCell<libc::pthread_rwlock_t> }
16 unsafe impl Send
for RWLock {}
17 unsafe impl Sync
for RWLock {}
20 pub const fn new() -> RWLock
{
21 RWLock { inner: UnsafeCell::new(libc::PTHREAD_RWLOCK_INITIALIZER) }
24 pub unsafe fn read(&self) {
25 let r
= libc
::pthread_rwlock_rdlock(self.inner
.get());
27 // According to the pthread_rwlock_rdlock spec, this function **may**
28 // fail with EDEADLK if a deadlock is detected. On the other hand
29 // pthread mutexes will *never* return EDEADLK if they are initialized
30 // as the "fast" kind (which ours always are). As a result, a deadlock
31 // situation may actually return from the call to pthread_rwlock_rdlock
32 // instead of blocking forever (as mutexes and Windows rwlocks do). Note
33 // that not all unix implementations, however, will return EDEADLK for
36 // We roughly maintain the deadlocking behavior by panicking to ensure
37 // that this lock acquisition does not succeed.
38 if r
== libc
::EDEADLK
{
39 panic
!("rwlock read lock would result in deadlock");
41 debug_assert_eq
!(r
, 0);
45 pub unsafe fn try_read(&self) -> bool
{
46 libc
::pthread_rwlock_tryrdlock(self.inner
.get()) == 0
49 pub unsafe fn write(&self) {
50 let r
= libc
::pthread_rwlock_wrlock(self.inner
.get());
51 // see comments above for why we check for EDEADLK
52 if r
== libc
::EDEADLK
{
53 panic
!("rwlock write lock would result in deadlock");
55 debug_assert_eq
!(r
, 0);
59 pub unsafe fn try_write(&self) -> bool
{
60 libc
::pthread_rwlock_trywrlock(self.inner
.get()) == 0
63 pub unsafe fn read_unlock(&self) {
64 let r
= libc
::pthread_rwlock_unlock(self.inner
.get());
65 debug_assert_eq
!(r
, 0);
68 pub unsafe fn write_unlock(&self) { self.read_unlock() }
70 pub unsafe fn destroy(&self) {
71 let r
= libc
::pthread_rwlock_destroy(self.inner
.get());
72 // On DragonFly pthread_rwlock_destroy() returns EINVAL if called on a
73 // rwlock that was just initialized with
74 // libc::PTHREAD_RWLOCK_INITIALIZER. Once it is used (locked/unlocked)
75 // or pthread_rwlock_init() is called, this behaviour no longer occurs.
76 if cfg
!(target_os
= "dragonfly") {
77 debug_assert
!(r
== 0 || r
== libc
::EINVAL
);
79 debug_assert_eq
!(r
, 0);