-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathCollectionTransformers.swift
1452 lines (1226 loc) · 38.5 KB
/
CollectionTransformers.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %target-run-stdlib-swift
// REQUIRES: executable_test
// FIXME: This test runs very slowly on watchOS.
// UNSUPPORTED: OS=watchos
import SwiftPrivate
public enum ApproximateCount {
case Unknown
case Precise(Int64)
case Underestimate(Int64)
case Overestimate(Int64)
}
public protocol ApproximateCountableSequence : Sequence {
/// Complexity: amortized O(1).
var approximateCount: ApproximateCount { get }
}
/// A collection that provides an efficient way to split its index ranges.
public protocol SplittableCollection : Collection {
// We need this protocol so that collections with only forward or bidirectional
// traversals could customize their splitting behavior.
//
// FIXME: all collections with random access should conform to this protocol
// automatically.
/// Splits a given range of indices into a set of disjoint ranges covering
/// the same elements.
///
/// Complexity: amortized O(1).
///
/// FIXME: should that be O(log n) to cover some strange collections?
///
/// FIXME: index invalidation rules?
///
/// FIXME: a better name. Users will never want to call this method
/// directly.
///
/// FIXME: return an optional for the common case when split() cannot
/// subdivide the range further.
func split(_ range: Range<Index>) -> [Range<Index>]
}
internal func _splitRandomAccessIndexRange<
C : RandomAccessCollection
>(
_ elements: C,
_ range: Range<C.Index>
) -> [Range<C.Index>] {
let startIndex = range.lowerBound
let endIndex = range.upperBound
let length = elements.distance(from: startIndex, to: endIndex)
if length < 2 {
return [range]
}
let middle = elements.index(startIndex, offsetBy: length / 2)
return [startIndex ..< middle, middle ..< endIndex]
}
/// A helper object to build a collection incrementally in an efficient way.
///
/// Using a builder can be more efficient than creating an empty collection
/// instance and adding elements one by one.
public protocol CollectionBuilder {
associatedtype Destination : Collection
associatedtype Element = Destination.Iterator.Element
init()
/// Gives a hint about the expected approximate number of elements in the
/// collection that is being built.
mutating func sizeHint(_ approximateSize: Int)
/// Append `element` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(1).
mutating func append(_ element: Destination.Iterator.Element)
/// Append `elements` to `self`.
///
/// If a collection being built supports a user-defined order, the element is
/// added at the end.
///
/// Complexity: amortized O(n), where `n` is equal to `count(elements)`.
mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == Element
/// Append elements from `otherBuilder` to `self`, emptying `otherBuilder`.
///
/// Equivalent to::
///
/// self.append(contentsOf: otherBuilder.takeResult())
///
/// but is more efficient.
///
/// Complexity: O(1).
mutating func moveContentsOf(_ otherBuilder: inout Self)
/// Build the collection from the elements that were added to this builder.
///
/// Once this function is called, the builder may not be reused and no other
/// methods should be called.
///
/// Complexity: O(n) or better (where `n` is the number of elements that were
/// added to this builder); typically O(1).
mutating func takeResult() -> Destination
}
public protocol BuildableCollectionProtocol : Collection {
associatedtype Builder : CollectionBuilder
}
extension Array : SplittableCollection {
public func split(_ range: Range<Int>) -> [Range<Int>] {
return _splitRandomAccessIndexRange(self, range)
}
}
public struct ArrayBuilder<T> : CollectionBuilder {
// FIXME: the compiler didn't complain when I remove public on 'Collection'.
// File a bug.
public typealias Destination = Array<T>
public typealias Element = T
internal var _resultParts = [[T]]()
internal var _resultTail = [T]()
public init() {}
public mutating func sizeHint(_ approximateSize: Int) {
_resultTail.reserveCapacity(approximateSize)
}
public mutating func append(_ element: T) {
_resultTail.append(element)
}
public mutating func append<
C : Collection
>(contentsOf elements: C)
where C.Iterator.Element == T {
_resultTail.append(contentsOf: elements)
}
public mutating func moveContentsOf(_ otherBuilder: inout ArrayBuilder<T>) {
// FIXME: do something smart with the capacity set in this builder and the
// other builder.
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: not O(1)!
_resultParts.append(contentsOf: otherBuilder._resultParts)
otherBuilder._resultParts = []
swap(&_resultTail, &otherBuilder._resultTail)
}
public mutating func takeResult() -> Destination {
_resultParts.append(_resultTail)
_resultTail = []
// FIXME: optimize. parallelize.
return Array(_resultParts.joined())
}
}
extension Array : BuildableCollectionProtocol {
public typealias Builder = ArrayBuilder<Element>
}
//===----------------------------------------------------------------------===//
// Fork-join
//===----------------------------------------------------------------------===//
// As sad as it is, I think for practical performance reasons we should rewrite
// the inner parts of the fork-join framework in C++. In way too many cases
// than necessary Swift requires an extra allocation to pin objects in memory
// for safe multithreaded access. -Dmitri
import SwiftShims
import SwiftPrivate
import Darwin
import Dispatch
// FIXME: port to Linux.
// XFAIL: OS=linux-gnu, OS=windows-msvc, OS=openbsd, OS=linux-android
// A wrapper for pthread_t with platform-independent interface.
public struct _stdlib_pthread_t : Equatable, Hashable {
internal let _value: pthread_t
public func hash(into hasher: inout Hasher) {
hasher.combine(_value)
}
}
public func == (lhs: _stdlib_pthread_t, rhs: _stdlib_pthread_t) -> Bool {
return lhs._value == rhs._value
}
public func _stdlib_pthread_self() -> _stdlib_pthread_t {
return _stdlib_pthread_t(_value: pthread_self())
}
struct _ForkJoinMutex {
var _mutex: UnsafeMutablePointer<pthread_mutex_t>
init() {
_mutex = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_mutex_init(_mutex, nil) != 0 {
fatalError("pthread_mutex_init")
}
}
func `deinit`() {
if pthread_mutex_destroy(_mutex) != 0 {
fatalError("pthread_mutex_init")
}
_mutex.deinitialize(count: 1)
_mutex.deallocate()
}
func withLock<Result>(_ body: () -> Result) -> Result {
if pthread_mutex_lock(_mutex) != 0 {
fatalError("pthread_mutex_lock")
}
let result = body()
if pthread_mutex_unlock(_mutex) != 0 {
fatalError("pthread_mutex_unlock")
}
return result
}
}
struct _ForkJoinCond {
var _cond: UnsafeMutablePointer<pthread_cond_t>
init() {
_cond = UnsafeMutablePointer.allocate(capacity: 1)
if pthread_cond_init(_cond, nil) != 0 {
fatalError("pthread_cond_init")
}
}
func `deinit`() {
if pthread_cond_destroy(_cond) != 0 {
fatalError("pthread_cond_destroy")
}
_cond.deinitialize(count: 1)
_cond.deallocate()
}
func signal() {
pthread_cond_signal(_cond)
}
func wait(_ mutex: _ForkJoinMutex) {
pthread_cond_wait(_cond, mutex._mutex)
}
}
final class _ForkJoinOneShotEvent {
var _mutex: _ForkJoinMutex = _ForkJoinMutex()
var _cond: _ForkJoinCond = _ForkJoinCond()
var _isSet: Bool = false
init() {}
deinit {
_cond.`deinit`()
_mutex.`deinit`()
}
func set() {
_mutex.withLock {
if !_isSet {
_isSet = true
_cond.signal()
}
}
}
/// Establishes a happens-before relation between calls to set() and wait().
func wait() {
_mutex.withLock {
while !_isSet {
_cond.wait(_mutex)
}
}
}
/// If the function returns true, it establishes a happens-before relation
/// between calls to set() and isSet().
func isSet() -> Bool {
return _mutex.withLock {
return _isSet
}
}
}
final class _ForkJoinWorkDeque<T> {
// FIXME: this is just a proof-of-concept; very inefficient.
// Implementation note: adding elements to the head of the deque is common in
// fork-join, so _deque is stored reversed (appending to an array is cheap).
// FIXME: ^ that is false for submission queues though.
var _deque: ContiguousArray<T> = []
var _dequeMutex: _ForkJoinMutex = _ForkJoinMutex()
init() {}
deinit {
precondition(_deque.isEmpty)
_dequeMutex.`deinit`()
}
var isEmpty: Bool {
return _dequeMutex.withLock {
return _deque.isEmpty
}
}
func prepend(_ element: T) {
_dequeMutex.withLock {
_deque.append(element)
}
}
func tryTakeFirst() -> T? {
return _dequeMutex.withLock {
let result = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return result
}
}
func tryTakeFirstTwo() -> (T?, T?) {
return _dequeMutex.withLock {
let result1 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
let result2 = _deque.last
if _deque.count > 0 {
_deque.removeLast()
}
return (result1, result2)
}
}
func append(_ element: T) {
_dequeMutex.withLock {
_deque.insert(element, at: 0)
}
}
func tryTakeLast() -> T? {
return _dequeMutex.withLock {
let result = _deque.first
if _deque.count > 0 {
_deque.remove(at: 0)
}
return result
}
}
func takeAll() -> ContiguousArray<T> {
return _dequeMutex.withLock {
let result = _deque
_deque = []
return result
}
}
func tryReplace(
_ value: T,
makeReplacement: @escaping () -> T,
isEquivalent: @escaping (T, T) -> Bool
) -> Bool {
return _dequeMutex.withLock {
for i in _deque.indices {
if isEquivalent(_deque[i], value) {
_deque[i] = makeReplacement()
return true
}
}
return false
}
}
}
final class _ForkJoinWorkerThread {
internal var _tid: _stdlib_pthread_t?
internal let _pool: ForkJoinPool
internal let _submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal let _workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
internal init(
_pool: ForkJoinPool,
submissionQueue: _ForkJoinWorkDeque<ForkJoinTaskBase>,
workDeque: _ForkJoinWorkDeque<ForkJoinTaskBase>
) {
self._tid = nil
self._pool = _pool
self._submissionQueue = submissionQueue
self._workDeque = workDeque
}
internal func startAsync() {
var queue: DispatchQueue?
if #available(OSX 10.10, iOS 8.0, *) {
queue = DispatchQueue.global(qos: .background)
} else {
queue = DispatchQueue.global(priority: .background)
}
queue!.async {
self._thread()
}
}
internal func _thread() {
print("_ForkJoinWorkerThread begin")
_tid = _stdlib_pthread_self()
outer: while !_workDeque.isEmpty || !_submissionQueue.isEmpty {
_pool._addRunningThread(self)
while true {
if _pool._tryStopThread() {
print("_ForkJoinWorkerThread detected too many threads")
_pool._removeRunningThread(self)
_pool._submitTasksToRandomWorkers(_workDeque.takeAll())
_pool._submitTasksToRandomWorkers(_submissionQueue.takeAll())
print("_ForkJoinWorkerThread end")
return
}
// Process tasks in FIFO order: first the work queue, then the
// submission queue.
if let task = _workDeque.tryTakeFirst() {
task._run()
continue
}
if let task = _submissionQueue.tryTakeFirst() {
task._run()
continue
}
print("_ForkJoinWorkerThread stealing tasks")
if let task = _pool._stealTask() {
task._run()
continue
}
// FIXME: steal from submission queues?
break
}
_pool._removeRunningThread(self)
}
assert(_workDeque.isEmpty)
assert(_submissionQueue.isEmpty)
_ = _pool._totalThreads.fetchAndAdd(-1)
print("_ForkJoinWorkerThread end")
}
internal func _forkTask(_ task: ForkJoinTaskBase) {
// Try to inflate the pool.
if !_pool._tryCreateThread({ task }) {
_workDeque.prepend(task)
}
}
internal func _waitForTask(_ task: ForkJoinTaskBase) {
while true {
if task._isComplete() {
return
}
// If the task is in work queue of the current thread, run the task.
if _workDeque.tryReplace(
task,
makeReplacement: { ForkJoinTask<()>() {} },
isEquivalent: { $0 === $1 }) {
// We found the task. Run it in-place.
task._run()
return
}
// FIXME: also check the submission queue, maybe the task is there?
// FIXME: try to find the task in other threads' queues.
// FIXME: try to find tasks that were forked from this task in other
// threads' queues. Help thieves by stealing those tasks back.
// At this point, we can't do any work to help with running this task.
// We can't start new work either (if we do, we might end up creating
// more in-flight work than we can chew, and crash with out-of-memory
// errors).
_pool._compensateForBlockedWorkerThread() {
task._blockingWait()
// FIXME: do a timed wait, and retry stealing.
}
}
}
}
internal protocol _Future {
associatedtype Result
/// Establishes a happens-before relation between completing the future and
/// the call to wait().
func wait()
func tryGetResult() -> Result?
func tryTakeResult() -> Result?
func waitAndGetResult() -> Result
func waitAndTakeResult() -> Result
}
public class ForkJoinTaskBase {
final internal var _pool: ForkJoinPool?
// FIXME(performance): there is no need to create heavy-weight
// synchronization primitives every time. We could start with a lightweight
// atomic int for the flag and inflate to a full event when needed. Unless
// we really need to block in wait(), we would avoid creating an event.
final internal let _completedEvent: _ForkJoinOneShotEvent =
_ForkJoinOneShotEvent()
final internal func _isComplete() -> Bool {
return _completedEvent.isSet()
}
final internal func _blockingWait() {
_completedEvent.wait()
}
internal func _run() {
fatalError("implement")
}
final public func fork() {
precondition(_pool == nil)
if let thread = ForkJoinPool._getCurrentThread() {
thread._forkTask(self)
} else {
// FIXME: decide if we want to allow this.
precondition(false)
ForkJoinPool.commonPool.forkTask(self)
}
}
final public func wait() {
if let thread = ForkJoinPool._getCurrentThread() {
thread._waitForTask(self)
} else {
_blockingWait()
}
}
}
final public class ForkJoinTask<Result> : ForkJoinTaskBase, _Future {
internal let _task: () -> Result
internal var _result: Result?
public init(_task: @escaping () -> Result) {
self._task = _task
}
override internal func _run() {
_complete(_task())
}
/// It is not allowed to call _complete() in a racy way. Only one thread
/// should ever call _complete().
internal func _complete(_ result: Result) {
precondition(!_completedEvent.isSet())
_result = result
_completedEvent.set()
}
public func tryGetResult() -> Result? {
if _completedEvent.isSet() {
return _result
}
return nil
}
public func tryTakeResult() -> Result? {
if _completedEvent.isSet() {
let result = _result
_result = nil
return result
}
return nil
}
public func waitAndGetResult() -> Result {
wait()
return tryGetResult()!
}
public func waitAndTakeResult() -> Result {
wait()
return tryTakeResult()!
}
}
final public class ForkJoinPool {
internal static var _threadRegistry: [_stdlib_pthread_t : _ForkJoinWorkerThread] = [:]
internal static var _threadRegistryMutex: _ForkJoinMutex = _ForkJoinMutex()
internal static func _getCurrentThread() -> _ForkJoinWorkerThread? {
return _threadRegistryMutex.withLock {
return _threadRegistry[_stdlib_pthread_self()]
}
}
internal let _maxThreads: Int
/// Total number of threads: number of running threads plus the number of
/// threads that are preparing to start).
internal let _totalThreads = _stdlib_AtomicInt(0)
internal var _runningThreads: [_ForkJoinWorkerThread] = []
internal var _runningThreadsMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _submissionQueues: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _submissionQueuesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal var _workDeques: [_ForkJoinWorkDeque<ForkJoinTaskBase>] = []
internal var _workDequesMutex: _ForkJoinMutex = _ForkJoinMutex()
internal init(_commonPool: ()) {
self._maxThreads = _stdlib_getHardwareConcurrency()
}
deinit {
_runningThreadsMutex.`deinit`()
_submissionQueuesMutex.`deinit`()
_workDequesMutex.`deinit`()
}
internal func _addRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
ForkJoinPool._threadRegistry[thread._tid!] = thread
_runningThreads.append(thread)
_submissionQueues.append(thread._submissionQueue)
_workDeques.append(thread._workDeque)
}
}
}
}
}
internal func _removeRunningThread(_ thread: _ForkJoinWorkerThread) {
ForkJoinPool._threadRegistryMutex.withLock {
_runningThreadsMutex.withLock {
_submissionQueuesMutex.withLock {
_workDequesMutex.withLock {
let i = _runningThreads.firstIndex { $0 === thread }!
ForkJoinPool._threadRegistry[thread._tid!] = nil
_runningThreads.remove(at: i)
_submissionQueues.remove(at: i)
_workDeques.remove(at: i)
}
}
}
}
}
internal func _compensateForBlockedWorkerThread(_ blockingBody: @escaping () -> ()) {
// FIXME: limit the number of compensating threads.
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
blockingBody()
_ = _totalThreads.fetchAndAdd(1)
}
internal func _tryCreateThread(
_ makeTask: () -> ForkJoinTaskBase?
) -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
if oldNumThreads >= _maxThreads {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads + 1)
} while !success
if let task = makeTask() {
let submissionQueue = _ForkJoinWorkDeque<ForkJoinTaskBase>()
let workDeque = _ForkJoinWorkDeque<ForkJoinTaskBase>()
workDeque.prepend(task)
let thread = _ForkJoinWorkerThread(
_pool: self, submissionQueue: submissionQueue, workDeque: workDeque)
thread.startAsync()
} else {
_ = _totalThreads.fetchAndAdd(-1)
}
return true
}
internal func _stealTask() -> ForkJoinTaskBase? {
return _workDequesMutex.withLock {
let randomOffset = _workDeques.indices.randomElement()!
let count = _workDeques.count
for i in _workDeques.indices {
let index = (i + randomOffset) % count
if let task = _workDeques[index].tryTakeLast() {
return task
}
}
return nil
}
}
/// Check if the pool has grown too large because of compensating
/// threads.
internal func _tryStopThread() -> Bool {
var success = false
var oldNumThreads = _totalThreads.load()
repeat {
// FIXME: magic number 2.
if oldNumThreads <= _maxThreads + 2 {
return false
}
success = _totalThreads.compareExchange(
expected: &oldNumThreads, desired: oldNumThreads - 1)
} while !success
return true
}
internal func _submitTasksToRandomWorkers<
C : Collection
>(_ tasks: C)
where C.Iterator.Element == ForkJoinTaskBase {
if tasks.isEmpty {
return
}
_submissionQueuesMutex.withLock {
precondition(!_submissionQueues.isEmpty)
for task in tasks {
_submissionQueues.randomElement()!.append(task)
}
}
}
public func forkTask(_ task: ForkJoinTaskBase) {
while true {
// Try to inflate the pool first.
if _tryCreateThread({ task }) {
return
}
// Looks like we can't create more threads. Submit the task to
// a random thread.
let done = _submissionQueuesMutex.withLock {
() -> Bool in
if !_submissionQueues.isEmpty {
_submissionQueues.randomElement()!.append(task)
return true
}
return false
}
if done {
return
}
}
}
// FIXME: return a Future instead?
public func forkTask<Result>(task: @escaping () -> Result) -> ForkJoinTask<Result> {
let forkJoinTask = ForkJoinTask(_task: task)
forkTask(forkJoinTask)
return forkJoinTask
}
public static var commonPool = ForkJoinPool(_commonPool: ())
public static func invokeAll(_ tasks: ForkJoinTaskBase...) {
ForkJoinPool.invokeAll(tasks)
}
public static func invokeAll(_ tasks: [ForkJoinTaskBase]) {
if tasks.isEmpty {
return
}
if ForkJoinPool._getCurrentThread() != nil {
// Run the first task in this thread, fork the rest.
let first = tasks.first
for t in tasks.dropFirst() {
// FIXME: optimize forking in bulk.
t.fork()
}
first!._run()
} else {
// FIXME: decide if we want to allow this.
precondition(false)
}
}
}
//===----------------------------------------------------------------------===//
// Collection transformation DSL: implementation
//===----------------------------------------------------------------------===//
internal protocol _CollectionTransformerStepProtocol /*: class*/ {
associatedtype PipelineInputElement
associatedtype OutputElement
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement
}
internal class _CollectionTransformerStep<PipelineInputElement_, OutputElement_>
: _CollectionTransformerStepProtocol {
typealias PipelineInputElement = PipelineInputElement_
typealias OutputElement = OutputElement_
func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
fatalError("abstract method")
}
func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
fatalError("abstract method")
}
func reduce<U>(_ initial: U, _ combine: @escaping (U, OutputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
fatalError("abstract method")
}
func collectTo<
C : BuildableCollectionProtocol
>(_: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
fatalError("abstract method")
}
func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
fatalError("abstract method")
}
}
final internal class _CollectionTransformerStepCollectionSource<
PipelineInputElement
> : _CollectionTransformerStep<PipelineInputElement, PipelineInputElement> {
typealias InputElement = PipelineInputElement
override func map<U>(_ transform: @escaping (InputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
return _CollectionTransformerStepOneToMaybeOne(self) {
transform($0)
}
}
override func filter(_ isIncluded: @escaping (InputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, InputElement> {
return _CollectionTransformerStepOneToMaybeOne(self) {
isIncluded($0) ? $0 : nil
}
}
override func reduce<U>(_ initial: U, _ combine: @escaping (U, InputElement) -> U)
-> _CollectionTransformerFinalizer<PipelineInputElement, U> {
return _CollectionTransformerFinalizerReduce(self, initial, combine)
}
override func collectTo<
C : BuildableCollectionProtocol
>(_ c: C.Type) -> _CollectionTransformerFinalizer<PipelineInputElement, C>
where
C.Builder.Destination == C,
C.Builder.Element == C.Iterator.Element,
C.Iterator.Element == OutputElement {
return _CollectionTransformerFinalizerCollectTo(self, c)
}
override func transform<
InputCollection : Collection,
Collector : _ElementCollector
>(
_ c: InputCollection,
_ range: Range<InputCollection.Index>,
_ collector: inout Collector
)
where
InputCollection.Iterator.Element == PipelineInputElement,
Collector.Element == OutputElement {
var i = range.lowerBound
while i != range.upperBound {
let e = c[i]
collector.append(e)
c.formIndex(after: &i)
}
}
}
final internal class _CollectionTransformerStepOneToMaybeOne<
PipelineInputElement,
OutputElement,
InputStep : _CollectionTransformerStepProtocol
> : _CollectionTransformerStep<PipelineInputElement, OutputElement>
where InputStep.PipelineInputElement == PipelineInputElement {
typealias _Self = _CollectionTransformerStepOneToMaybeOne
typealias InputElement = InputStep.OutputElement
let _input: InputStep
let _transform: (InputElement) -> OutputElement?
init(_ input: InputStep, _ transform: @escaping (InputElement) -> OutputElement?) {
self._input = input
self._transform = transform
super.init()
}
override func map<U>(_ transform: @escaping (OutputElement) -> U)
-> _CollectionTransformerStep<PipelineInputElement, U> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, U, InputStep>(_input) {
(input: InputElement) -> U? in
if let e = localTransform(input) {
return transform(e)
}
return nil
}
}
override func filter(_ isIncluded: @escaping (OutputElement) -> Bool)
-> _CollectionTransformerStep<PipelineInputElement, OutputElement> {
// Let the closure below capture only one variable, not the whole `self`.
let localTransform = _transform
return _CollectionTransformerStepOneToMaybeOne<PipelineInputElement, OutputElement, InputStep>(_input) {