Skip to content

Commit 38377df

Browse files
author
Chris Amanse
committed
Fix memory leaks in ThreadBarriers.swift
1 parent 66afe77 commit 38377df

File tree

1 file changed

+18
-13
lines changed

1 file changed

+18
-13
lines changed

stdlib/private/SwiftPrivateThreadExtras/ThreadBarriers.swift

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -69,33 +69,38 @@ public func _stdlib_thread_barrier_init(
6969
InitializeConditionVariable(barrier.pointee.cond!)
7070
#else
7171
barrier.pointee.mutex = UnsafeMutablePointer.allocate(capacity: 1)
72-
if pthread_mutex_init(barrier.pointee.mutex!, nil) != 0 {
73-
// FIXME: leaking memory.
74-
return -1
75-
}
7672
barrier.pointee.cond = UnsafeMutablePointer.allocate(capacity: 1)
77-
if pthread_cond_init(barrier.pointee.cond!, nil) != 0 {
78-
// FIXME: leaking memory, leaking a mutex.
79-
return -1
73+
guard _stdlib_pthread_barrier_mutex_and_cond_init(barrier) == 0 else {
74+
barrier.pointee.mutex!.deinitialize(count: 1)
75+
barrier.pointee.mutex!.deallocate()
76+
barrier.pointee.cond!.deinitialize(count: 1)
77+
barrier.pointee.cond!.deallocate()
8078
}
8179
#endif
8280
barrier.pointee.count = count
8381
return 0
8482
}
8583

84+
private func _stdlib_pthread_barrier_mutex_and_cond_init(_ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>) -> CInt {
85+
guard pthread_mutex_init(barrier.pointee.mutex!) == 0 else {
86+
return -1
87+
}
88+
guard pthread_cond_init(barrier.pointee.cond!) == 0 else {
89+
pthread_mutex_destroy(barrier.pointee.mutex!)
90+
return -1
91+
}
92+
return 0
93+
}
94+
8695
public func _stdlib_thread_barrier_destroy(
8796
_ barrier: UnsafeMutablePointer<_stdlib_thread_barrier_t>
8897
) -> CInt {
8998
#if os(Windows)
9099
// Condition Variables do not need to be explicitly destroyed
91100
// Mutexes do not need to be explicitly destroyed
92101
#else
93-
if pthread_cond_destroy(barrier.pointee.cond!) != 0 {
94-
// FIXME: leaking memory, leaking a mutex.
95-
return -1
96-
}
97-
if pthread_mutex_destroy(barrier.pointee.mutex!) != 0 {
98-
// FIXME: leaking memory.
102+
guard pthread_cond_destroy(barrier.pointee.cond!) == 0 &&
103+
pthread_mutex_destroy(barrier.pointee.mutex!) == 0 else {
99104
return -1
100105
}
101106
#endif

0 commit comments

Comments
 (0)