Skip to content

Commit 1c8b72d

Browse files
committed
added test for ReadWriteLock
1 parent 7af71b1 commit 1c8b72d

File tree

2 files changed

+48
-3
lines changed

2 files changed

+48
-3
lines changed

Sources/TSCBasic/Lock.swift

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,27 @@ public class ReadWriteLock {
4141
pthread_rwlock_init(&lock, nil)
4242
}
4343

44+
func readLock() {
45+
pthread_rwlock_rdlock(&lock)
46+
}
47+
48+
func writeLock() {
49+
pthread_rwlock_wrlock(&lock)
50+
}
51+
52+
func unlock() {
53+
pthread_rwlock_unlock(&lock)
54+
}
55+
4456
/// Execute the given block while holding the lock.
4557
public func withLock<T>(type lockType: LockType = .exclusive, _ body: () throws -> T) rethrows -> T {
4658
switch lockType {
4759
case .shared:
48-
pthread_rwlock_rdlock(&lock)
60+
readLock()
4961
case .exclusive:
50-
pthread_rwlock_wrlock(&lock)
62+
writeLock()
5163
}
52-
defer { pthread_rwlock_unlock(&lock) }
64+
defer { unlock() }
5365
return try body()
5466
}
5567

Tests/TSCBasicTests/LockTests.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,4 +48,37 @@ class LockTests: XCTestCase {
4848
}
4949
}
5050
}
51+
52+
func testReadWriteLock() throws {
53+
var a = 0
54+
var b = 0
55+
56+
let lock = ReadWriteLock()
57+
58+
let writerThreads = (0..<100).map { _ in
59+
return Thread {
60+
lock.withLock(type: .exclusive) {
61+
a+=1
62+
sched_yield()
63+
b+=1
64+
}
65+
}
66+
}
67+
68+
let readerThreads = (0..<20).map { _ in
69+
return Thread {
70+
lock.withLock(type: .shared) {
71+
XCTAssertEqual(a,b)
72+
sched_yield()
73+
XCTAssertEqual(a,b)
74+
}
75+
}
76+
}
77+
78+
writerThreads.forEach { $0.start() }
79+
readerThreads.forEach { $0.start() }
80+
writerThreads.forEach { $0.join() }
81+
readerThreads.forEach { $0.join() }
82+
}
83+
5184
}

0 commit comments

Comments
 (0)