vibe.core.sync 14/431(3%) line coverage

      
10
20
30
40
50
60
70
80
90
100
110
120
130
140
150
160
170
180
190
200
210
220
230
240
250
260
270
280
290
300
310
320
331
340
350
360
370
380
390
400
410
420
430
440
450
460
470
480
490
500
510
520
530
540
550
560
570
580
590
600
610
620
630
640
650
660
670
680
690
700
710
720
730
740
750
760
770
780
790
800
810
820
830
840
850
860
870
880
890
900
910
920
930
940
950
960
970
980
990
1000
1010
1020
1030
1040
1050
1060
1070
1080
1090
1100
1110
1120
1130
1140
1150
1160
1170
1180
1190
1200
1210
1220
1230
1240
1250
1260
1270
1280
1290
1300
1310
1320
1330
1340
1350
1360
1370
1380
1390
1400
1410
1420
1430
1440
1450
1460
1470
1480
1490
1500
1510
1520
1530
1540
1550
1560
1570
1580
1590
1600
1610
1620
1630
1640
1650
1660
1670
1680
1690
1700
1710
1720
1730
1740
1750
1760
1770
1780
1790
1800
1810
1820
1830
1840
1850
1860
1870
1880
1890
1900
1910
1920
1930
1940
1950
1960
1970
1980
1990
2000
2010
2020
2030
2040
2050
2060
2070
2080
2090
2100
2110
2120
2130
2140
2150
2160
2170
2180
2190
2200
2210
2220
2230
2240
2250
2260
2270
2280
2290
2300
2310
2320
2330
2340
2350
2360
2370
2380
2390
2400
2410
2420
2430
2440
2450
2460
2470
2480
2490
2500
2510
2520
2530
2540
2550
2560
2570
2580
2590
2600
2610
2620
2630
2640
2650
2660
2670
2680
2690
2700
2710
2720
2730
2740
2750
2760
2770
2780
2790
2800
2810
2820
2830
2840
2850
2860
2870
2880
2890
2900
2910
2920
2930
2940
2950
2960
2970
2980
2990
3000
3010
3020
3030
3040
3050
3060
3070
3080
3090
3100
3110
3120
3130
3140
3150
3160
3170
3180
3190
3200
3210
3220
3230
3240
3250
3260
3270
3280
3290
3300
3310
3320
3330
3340
3350
3360
3370
3380
3390
3400
3410
3420
3430
3440
3450
3460
3470
3480
3490
3500
3510
3520
3530
3540
3550
3560
3570
3580
3590
3600
3610
3620
3630
3640
3650
3660
3670
3680
3690
3700
3710
3720
3730
3740
3750
3760
3770
3780
37982
3800
3810
38212
38312
3840
3850
3860
3870
3880
3890
3900
3910
3920
3930
3940
3950
3960
3970
3980
3990
4000
4010
4020
4030
4040
4050
4060
4070
4080
4090
4100
4110
4120
4130
4140
4150
4160
4170
4180
4190
4200
4210
4220
4230
4240
4250
4260
4270
4280
4290
4300
4310
4320
4330
4340
4350
4360
4370
4380
4390
4400
4410
4420
4430
4440
4450
4460
4470
4480
4490
4500
4510
4520
4530
4540
4550
4560
4570
4580
4590
4600
4610
4620
4630
4640
4650
4660
4670
4680
4690
4700
4710
4720
4730
4740
4750
4760
4770
4780
4790
4800
4810
4820
4830
4840
4850
4860
4870
4880
4890
4900
4910
4920
4930
4940
4950
4960
4970
4980
4990
5000
5010
5020
5030
5040
5050
5060
5070
5080
5090
5100
5110
5120
5130
5140
5150
5160
5170
5180
5190
5200
5210
5220
5230
5240
5250
5260
5270
5280
5290
5300
5310
5320
5330
5340
5350
5360
5370
5380
5390
5400
5410
5420
5430
5440
5450
5460
5470
5480
5490
5500
5510
5520
5530
5540
5550
5560
5570
5580
5590
5600
5610
5620
5630
5640
5650
5660
5670
5680
5690
5700
5710
5720
5730
5740
5750
5760
5770
5780
5790
5800
5810
5820
5830
5840
5850
5860
5870
5880
5890
5900
5910
5920
5930
5940
5950
5960
5970
5980
5990
6000
6010
6020
6030
6040
6050
6060
6070
6080
6090
6100
6110
6120
6130
6140
6150
6160
6170
6180
6190
6200
6210
6220
6230
6240
6250
6260
6270
6280
6290
6300
6310
6320
6330
6340
6350
6360
6370
6380
6390
6400
6410
6420
6430
6440
6450
6460
6470
6480
6490
6500
6510
6520
6530
6540
6550
6560
6570
6580
6590
6600
6610
6620
6630
6640
6650
6660
6670
6680
6690
6700
6710
6720
6730
6740
6750
6760
6770
6780
6790
6800
6810
6820
6830
6840
6850
6860
6870
6880
6890
6900
6910
6920
6930
6940
6950
6960
6970
6980
6990
7000
7010
7020
7030
7040
7050
7060
7070
7080
7090
7100
7110
7120
7130
7140
7150
7160
7170
7180
7190
7200
7210
7220
7230
7240
7250
7260
7270
7280
7290
7300
7310
7320
7330
7340
7350
7360
7370
7380
7390
7400
7410
7420
7430
7440
7450
7460
7470
7480
7490
7500
7510
7520
7530
7540
7550
7560
7570
7580
7590
7600
7610
7620
7630
7640
7650
7660
7670
7680
7690
7700
7710
7720
7730
7740
7750
7760
7770
7780
7790
7800
7810
7820
7830
7840
7850
7860
7870
7880
7890
7900
7910
7920
7930
7940
7950
7960
7970
7980
7990
8000
8010
8020
8030
8040
8050
8060
8070
8080
8090
8100
8110
8120
8130
8140
8150
8160
8170
8180
8190
8200
8210
8220
8230
8240
8250
8260
8270
8280
8290
8300
8310
8320
8330
8340
8350
8360
8370
8380
8390
8400
8410
8420
8430
8440
8450
8460
8470
8480
8490
8500
8510
8520
8530
8540
8550
8560
8570
8580
8590
8600
8610
8620
8630
8640
8650
8660
8670
8680
8690
8700
8710
8720
8730
8740
8750
8760
8770
8780
8790
8800
8810
8820
8830
8840
8850
8860
8870
8880
8890
8900
8910
8920
8930
8940
8950
8960
8970
8980
8990
9000
9010
9020
9030
9040
9050
9060
9070
9080
9090
9100
9110
9120
9130
9140
9150
9160
9170
9180
9190
9200
9210
9220
9230
9240
9250
9260
9270
9280
9290
9300
9310
9320
9330
9340
9350
9360
9370
9380
9390
9400
9410
9420
9430
9440
9450
9460
9470
9480
9490
9500
9510
9520
9530
9540
9550
9560
9570
9580
9590
9600
9610
9620
9630
9640
9650
9660
9670
9680
9690
9700
9710
9720
9730
9740
9750
9760
9770
9780
9790
9800
9810
9820
9830
9840
9850
9860
9870
9880
9890
9900
9910
9920
9930
9940
9950
9960
9970
9980
9990
10000
10010
10020
10030
10040
10050
10060
10070
10080
10090
10100
10110
10120
10130
10140
10150
10160
10170
10180
10190
10200
10210
10220
10230
10240
10250
10260
10270
10280
10290
10300
10310
10320
10330
10340
10350
10360
10370
10380
10390
10400
10410
10420
10430
10440
10450
10460
10470
10480
10490
10500
10510
10520
10530
10540
10550
10560
10570
10580
10590
10600
10610
10620
10630
10640
10650
10660
10670
10680
10690
10700
10710
10720
10730
10740
10750
10760
10770
10780
10790
10800
10810
10820
10830
10840
10850
10860
10870
10880
10890
10900
10910
10920
10930
10940
10950
10960
10970
10980
10990
11000
11010
11020
11030
11040
11050
11060
11070
11080
11090
11100
11110
11120
11130
11140
11150
11160
11170
11180
11190
11200
11210
11220
11230
11240
11250
11260
11270
11280
11290
11300
11310
11320
11330
11340
11350
11360
11370
11380
11390
11400
11410
11420
11430
11440
11450
11460
11470
11480
11490
11500
11510
11520
11530
11540
11550
11560
11570
11580
11590
11600
11610
11620
11630
11640
11650
11660
11670
11680
11690
11700
11710
11720
11730
11740
11750
11760
11770
11780
11790
11800
11810
11820
11830
11840
11850
11860
11870
11880
11890
11900
11910
11920
11930
11940
11950
11960
11970
11980
11990
12000
12010
12020
12030
12040
12050
12060
12070
12080
120913
12100
12110
12120
12130
12140
12150
12160
12170
12180
12190
12200
12210
12220
12230
12240
12250
12260
12270
12280
12290
12300
12310
12320
12330
12340
12350
12360
12370
12380
12390
12400
12410
12420
12430
12440
12450
12460
12470
12480
12490
12500
12510
12520
12530
12540
12550
12560
12570
12580
12590
12600
12610
12620
12630
12640
12650
12660
12670
12680
12690
12700
12710
12720
12730
12740
12750
12760
12770
12780
12790
12800
12810
12820
12830
12840
12850
12860
12870
12880
12890
12900
12910
12920
12930
12940
12950
12960
12970
12980
12990
13000
13010
13020
13030
13040
13050
13060
13070
13080
13090
13100
13110
13120
13130
13140
13150
13160
13170
13180
13190
13200
13210
13220
13230
13240
13250
13260
13270
13280
13290
13300
13310
13320
13330
13340
13350
13360
13370
13380
13390
13400
13410
13420
13430
13440
13450
13460
13470
13480
13490
13500
13510
13520
13530
13540
13550
13560
13570
13580
13590
13600
13610
13620
13630
13640
13650
13660
13670
13680
13690
13700
13710
13720
13730
13740
13750
13760
13770
13780
13790
13800
13810
13820
13830
13840
13850
13860
13870
13880
13890
13900
13910
13920
13930
13940
13950
13960
13970
13980
13990
14000
14010
14020
14030
14040
14050
14060
14070
14080
14090
14100
14110
141212
141312
14140
141512
14160
14170
14180
14190
14200
14210
142224
14230
14240
14250
14260
14270
14280
14290
14300
14310
14320
14330
14340
14350
143612
14370
143812
143912
14400
144112
14420
144312
14440
14450
14460
14470
14480
14490
14500
14510
14520
14530
14540
14550
14560
14570
14580
14590
14600
14610
14620
14630
14640
14650
14660
14670
14680
14690
14700
14710
14720
14730
14740
14750
14760
14770
14780
14790
14800
14810
14820
14830
14840
14850
14860
14870
14880
14890
14900
14910
14920
14930
14940
14950
14960
14970
14980
14990
15000
15010
15020
15030
15040
15050
15060
15070
15080
15090
15100
15110
15120
15130
15140
15150
15160
15170
15180
15190
15200
15210
15220
15230
15240
15250
15260
15270
15280
15290
15300
15310
15320
15330
15340
15350
15360
15370
15380
15390
15400
15410
15420
15430
15440
15450
15460
15470
15480
15490
15500
15510
15520
15530
15540
15550
15560
15570
15580
15590
15600
15610
15620
15630
15640
15650
15660
15670
15680
15690
15700
15710
15720
15730
15740
15750
15760
15770
15780
15790
15800
15810
15820
15830
15840
15850
15860
15870
15880
15890
15900
15910
15920
15930
15940
15950
15960
15970
15980
15990
16000
16010
16020
16030
16040
16050
16060
16070
16080
16090
16100
16110
16120
16130
16140
16150
16160
16170
16180
16190
16200
16210
16220
16230
16240
16250
16260
16270
16280
16290
16300
16310
16320
16330
16340
16350
16360
16370
16380
16390
16400
16410
16420
16430
16440
16450
16460
16470
16480
16490
16500
16510
16520
16530
16540
16550
16560
16570
16580
16590
16600
16610
16620
16630
16640
16650
16660
16670
16680
16690
16700
16710
16720
16730
16740
16750
16760
16770
16780
16790
16800
16810
16820
16830
16840
16850
16860
16870
16880
16890
16900
16910
16920
16930
16940
16950
16960
16970
16980
16990
17000
17010
17020
17030
17040
17050
17060
17070
17080
17090
17100
17110
17120
17130
17140
17150
17160
17170
17180
17190
17200
17210
17220
17230
17240
17250
17260
17270
17280
17290
17300
17310
17320
17330
17340
17350
17360
17370
17380
17390
17400
17410
17420
17430
17440
17450
17460
17470
17480
17490
17500
17510
17520
17530
17540
17550
17560
17570
17580
17590
17600
17610
17620
17630
17640
17650
17660
17670
17680
17690
17700
17710
17720
17730
17740
17750
17760
17770
17780
17790
17800
17810
17820
17830
17840
17850
17860
17870
17880
17890
17900
17910
17920
17930
17940
17950
17960
17970
17980
17990
18000
18010
18020
18030
18040
18050
18060
18070
18080
18090
18100
18110
18120
18130
18140
18150
18160
18170
18180
18190
18200
18210
18220
18230
18240
18250
18260
18270
18280
18290
18300
18310
18320
18330
18340
18350
18360
18370
18380
18390
18400
18410
18420
18430
18440
18450
18460
18470
18480
18490
18500
18510
18520
18530
18540
18550
18560
18570
18580
18590
18600
18610
18620
18630
18640
18650
18660
18670
18680
18690
18700
18710
18720
18730
18740
18750
18760
18770
18780
18790
18800
18810
18820
18830
18840
18850
18860
18870
18880
18890
18900
18910
18920
18930
18940
18950
18960
18970
18980
18990
19000
19010
19020
19030
19040
19050
19060
19070
19080
19090
19100
19110
19120
19130
19140
19150
19160
19170
19180
19190
19200
19210
19220
19230
19240
19250
19260
19270
19280
19290
19300
19310
19320
19330
19340
19350
19360
19370
19380
19390
19400
19410
19420
19430
19440
19450
19460
19470
19480
19490
19500
19510
19520
19530
19540
19550
19560
19570
19580
19590
19600
19610
19620
19630
19640
19650
19660
19670
19680
19690
19700
19710
19720
19730
19740
19750
19760
19770
19780
19790
19800
19810
19820
19830
19840
19850
19860
19870
19880
19890
19900
19910
19920
19930
19940
19950
19960
19970
19980
19990
20000
20010
20020
20030
20040
20050
20060
20070
20080
20090
20100
20110
20120
20130
20140
20150
20160
20170
20180
20190
20200
20210
20220
20230
20240
20250
20260
20270
20280
20290
20300
20310
20320
20330
20340
20350
20360
20370
20380
20390
20400
20410
20420
20430
20440
20450
20460
20470
/** Interruptible Task synchronization facilities Copyright: © 2012-2016 RejectedSoftware e.K. Authors: Leonid Kramer, Sönke Ludwig, Manuel Frischknecht License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file. */ module vibe.core.sync; import vibe.core.log : logDebugV, logTrace, logInfo; import vibe.core.task; import core.atomic; import core.sync.mutex; import core.sync.condition; import eventcore.core; import std.exception; import std.stdio; import std.traits : ReturnType; /** Creates a new signal that can be shared between fibers. */ LocalManualEvent createManualEvent() @safe { LocalManualEvent ret; ret.initialize(); return ret; } /// ditto shared(ManualEvent) createSharedManualEvent() @trusted { return shared(ManualEvent).init; } ScopedMutexLock!M scopedMutexLock(M : Mutex)(M mutex, LockMode mode = LockMode.lock) { return ScopedMutexLock!M(mutex, mode); } enum LockMode { lock, tryLock, defer } interface Lockable { @safe: void lock(); void unlock(); bool tryLock(); } /** RAII lock for the Mutex class. */ struct ScopedMutexLock(M : Mutex = core.sync.mutex.Mutex) { @disable this(this); private { M m_mutex; bool m_locked; LockMode m_mode; } this(M mutex, LockMode mode = LockMode.lock) { assert(mutex !is null); m_mutex = mutex; final switch (mode) { case LockMode.lock: lock(); break; case LockMode.tryLock: tryLock(); break; case LockMode.defer: break; } } ~this() { if( m_locked ) m_mutex.unlock(); } @property bool locked() const { return m_locked; } void unlock() { enforce(m_locked); m_mutex.unlock(); m_locked = false; } bool tryLock() { enforce(!m_locked); return m_locked = m_mutex.tryLock(); } void lock() { enforce(!m_locked); m_locked = true; m_mutex.lock(); } } /* Only for internal use: Ensures that a mutex is locked while executing the given procedure. This function works for all kinds of mutexes, in particular for $(D core.sync.mutex.Mutex), $(D TaskMutex) and $(D InterruptibleTaskMutex). Returns: Returns the value returned from $(D PROC), if any. */ /// private ReturnType!PROC performLocked(alias PROC, MUTEX)(MUTEX mutex) { mutex.lock(); scope (exit) mutex.unlock(); return PROC(); } /// unittest { int protected_var = 0; auto mtx = new TaskMutex; mtx.performLocked!({ protected_var++; }); } /** Thread-local semaphore implementation for tasks. When the semaphore runs out of concurrent locks, it will suspend. This class is used in `vibe.core.connectionpool` to limit the number of concurrent connections. */ final class LocalTaskSemaphore { @safe: // requires a queue import std.container.binaryheap; import std.container.array; //import vibe.utils.memory; private { static struct ThreadWaiter { ubyte priority; uint seq; } BinaryHeap!(Array!ThreadWaiter, asc) m_waiters; uint m_maxLocks; uint m_locks; uint m_seq; LocalManualEvent m_signal; } this(uint max_locks) { m_maxLocks = max_locks; m_signal = createManualEvent(); } /// Maximum number of concurrent locks @property void maxLocks(uint max_locks) { m_maxLocks = max_locks; } /// ditto @property uint maxLocks() const { return m_maxLocks; } /// Number of concurrent locks still available @property uint available() const { return m_maxLocks - m_locks; } /** Try to acquire a lock. If a lock cannot be acquired immediately, returns `false` and leaves the semaphore in its previous state. Returns: `true` is returned $(I iff) the number of available locks is greater than one. */ bool tryLock() { if (available > 0) { m_locks++; return true; } return false; } /** Acquires a lock. Once the limit of concurrent locks is reached, this method will block until the number of locks drops below the limit. */ void lock(ubyte priority = 0) { import std.algorithm.comparison : min; if (tryLock()) return; ThreadWaiter w; w.priority = priority; w.seq = min(0, m_seq - w.priority); if (++m_seq == uint.max) rewindSeq(); () @trusted { m_waiters.insert(w); } (); while (true) { m_signal.waitUninterruptible(); if (m_waiters.front.seq == w.seq && tryLock()) { return; } } } /** Gives up an existing lock. */ void unlock() { assert(m_locks >= 1); m_locks--; if (m_waiters.length > 0) m_signal.emit(); // resume one } // if true, a goes after b. ie. b comes out front() /// private static bool asc(ref ThreadWaiter a, ref ThreadWaiter b) { if (a.priority != b.priority) return a.priority < b.priority; return a.seq > b.seq; } private void rewindSeq() @trusted { Array!ThreadWaiter waiters = m_waiters.release(); ushort min_seq; import std.algorithm : min; foreach (ref waiter; waiters[]) min_seq = min(waiter.seq, min_seq); foreach (ref waiter; waiters[]) waiter.seq -= min_seq; m_waiters.assume(waiters); } } /** Mutex implementation for fibers. This mutex type can be used in exchange for a core.sync.mutex.Mutex, but does not block the event loop when contention happens. Note that this mutex does not allow recursive locking. Notice: Because this class is annotated nothrow, it cannot be interrupted using $(D vibe.core.task.Task.interrupt()). The corresponding $(D InterruptException) will be deferred until the next blocking operation yields the event loop. Use $(D InterruptibleTaskMutex) as an alternative that can be interrupted. See_Also: InterruptibleTaskMutex, RecursiveTaskMutex, core.sync.mutex.Mutex */ final class TaskMutex : core.sync.mutex.Mutex, Lockable { @safe: private TaskMutexImpl!false m_impl; this(Object o) { m_impl.setup(); super(o); } this() { m_impl.setup(); } override bool tryLock() nothrow { return m_impl.tryLock(); } override void lock() nothrow { m_impl.lock(); } override void unlock() nothrow { m_impl.unlock(); } } unittest { auto mutex = new TaskMutex; { auto lock = scopedMutexLock(mutex); assert(lock.locked); assert(mutex.m_impl.m_locked); auto lock2 = scopedMutexLock(mutex, LockMode.tryLock); assert(!lock2.locked); } assert(!mutex.m_impl.m_locked); auto lock = scopedMutexLock(mutex, LockMode.tryLock); assert(lock.locked); lock.unlock(); assert(!lock.locked); synchronized(mutex){ assert(mutex.m_impl.m_locked); } assert(!mutex.m_impl.m_locked); mutex.performLocked!({ assert(mutex.m_impl.m_locked); }); assert(!mutex.m_impl.m_locked); static if (__VERSION__ >= 2067) { with(mutex.scopedMutexLock) { assert(mutex.m_impl.m_locked); } } } unittest { // test deferred throwing import vibe.core.core; auto mutex = new TaskMutex; auto t1 = runTask({ scope (failure) assert(false, "No exception expected in first task!"); mutex.lock(); scope (exit) mutex.unlock(); sleep(20.msecs); }); auto t2 = runTask({ mutex.lock(); scope (exit) mutex.unlock(); try { yield(); assert(false, "Yield is supposed to have thrown an InterruptException."); } catch (InterruptException) { // as expected! } catch (Exception) { assert(false, "Only InterruptException supposed to be thrown!"); } }); runTask({ // mutex is now locked in first task for 20 ms // the second tasks is waiting in lock() t2.interrupt(); t1.join(); t2.join(); assert(!mutex.m_impl.m_locked); // ensure that the scope(exit) has been executed exitEventLoop(); }); runEventLoop(); } unittest { runMutexUnitTests!TaskMutex(); } /** Alternative to $(D TaskMutex) that supports interruption. This class supports the use of $(D vibe.core.task.Task.interrupt()) while waiting in the $(D lock()) method. However, because the interface is not $(D nothrow), it cannot be used as an object monitor. See_Also: $(D TaskMutex), $(D InterruptibleRecursiveTaskMutex) */ final class InterruptibleTaskMutex : Lockable { @safe: private TaskMutexImpl!true m_impl; this() { m_impl.setup(); } bool tryLock() nothrow { return m_impl.tryLock(); } void lock() { m_impl.lock(); } void unlock() nothrow { m_impl.unlock(); } } version (VibeLibevDriver) {} else // timers are not implemented for libev, yet unittest { runMutexUnitTests!InterruptibleTaskMutex(); } /** Recursive mutex implementation for tasks. This mutex type can be used in exchange for a core.sync.mutex.Mutex, but does not block the event loop when contention happens. Notice: Because this class is annotated nothrow, it cannot be interrupted using $(D vibe.core.task.Task.interrupt()). The corresponding $(D InterruptException) will be deferred until the next blocking operation yields the event loop. Use $(D InterruptibleRecursiveTaskMutex) as an alternative that can be interrupted. See_Also: TaskMutex, core.sync.mutex.Mutex */ final class RecursiveTaskMutex : core.sync.mutex.Mutex, Lockable { @safe: private RecursiveTaskMutexImpl!false m_impl; this(Object o) { m_impl.setup(); super(o); } this() { m_impl.setup(); } override bool tryLock() { return m_impl.tryLock(); } override void lock() { m_impl.lock(); } override void unlock() { m_impl.unlock(); } } version (VibeLibevDriver) {} else // timers are not implemented for libev, yet unittest { runMutexUnitTests!RecursiveTaskMutex(); } /** Alternative to $(D RecursiveTaskMutex) that supports interruption. This class supports the use of $(D vibe.core.task.Task.interrupt()) while waiting in the $(D lock()) method. However, because the interface is not $(D nothrow), it cannot be used as an object monitor. See_Also: $(D RecursiveTaskMutex), $(D InterruptibleTaskMutex) */ final class InterruptibleRecursiveTaskMutex : Lockable { @safe: private RecursiveTaskMutexImpl!true m_impl; this() { m_impl.setup(); } bool tryLock() { return m_impl.tryLock(); } void lock() { m_impl.lock(); } void unlock() { m_impl.unlock(); } } version (VibeLibevDriver) {} else // timers are not implemented for libev, yet unittest { runMutexUnitTests!InterruptibleRecursiveTaskMutex(); } private void runMutexUnitTests(M)() { import vibe.core.core; auto m = new M; Task t1, t2; void runContendedTasks(bool interrupt_t1, bool interrupt_t2) { assert(!m.m_impl.m_locked); // t1 starts first and acquires the mutex for 20 ms // t2 starts second and has to wait in m.lock() t1 = runTask({ assert(!m.m_impl.m_locked); m.lock(); assert(m.m_impl.m_locked); if (interrupt_t1) assertThrown!InterruptException(sleep(100.msecs)); else assertNotThrown(sleep(20.msecs)); m.unlock(); }); t2 = runTask({ assert(!m.tryLock()); if (interrupt_t2) { try m.lock(); catch (InterruptException) return; try yield(); // rethrows any deferred exceptions catch (InterruptException) { m.unlock(); return; } assert(false, "Supposed to have thrown an InterruptException."); } else assertNotThrown(m.lock()); assert(m.m_impl.m_locked); sleep(20.msecs); m.unlock(); assert(!m.m_impl.m_locked); }); } // basic lock test m.performLocked!({ assert(m.m_impl.m_locked); }); assert(!m.m_impl.m_locked); // basic contention test runContendedTasks(false, false); auto t3 = runTask({ assert(t1.running && t2.running); assert(m.m_impl.m_locked); t1.join(); assert(!t1.running && t2.running); yield(); // give t2 a chance to take the lock assert(m.m_impl.m_locked); t2.join(); assert(!t2.running); assert(!m.m_impl.m_locked); exitEventLoop(); }); runEventLoop(); assert(!t3.running); assert(!m.m_impl.m_locked); // interruption test #1 runContendedTasks(true, false); t3 = runTask({ assert(t1.running && t2.running); assert(m.m_impl.m_locked); t1.interrupt(); t1.join(); assert(!t1.running && t2.running); yield(); // give t2 a chance to take the lock assert(m.m_impl.m_locked); t2.join(); assert(!t2.running); assert(!m.m_impl.m_locked); exitEventLoop(); }); runEventLoop(); assert(!t3.running); assert(!m.m_impl.m_locked); // interruption test #2 runContendedTasks(false, true); t3 = runTask({ assert(t1.running && t2.running); assert(m.m_impl.m_locked); t2.interrupt(); t2.join(); assert(!t2.running); static if (is(M == InterruptibleTaskMutex) || is (M == InterruptibleRecursiveTaskMutex)) assert(t1.running && m.m_impl.m_locked); t1.join(); assert(!t1.running); assert(!m.m_impl.m_locked); exitEventLoop(); }); runEventLoop(); assert(!t3.running); assert(!m.m_impl.m_locked); } /** Event loop based condition variable or "event" implementation. This class can be used in exchange for a $(D core.sync.condition.Condition) to avoid blocking the event loop when waiting. Notice: Because this class is annotated nothrow, it cannot be interrupted using $(D vibe.core.task.Task.interrupt()). The corresponding $(D InterruptException) will be deferred until the next blocking operation yields to the event loop. Use $(D InterruptibleTaskCondition) as an alternative that can be interrupted. Note that it is generally not safe to use a `TaskCondition` together with an interruptible mutex type. See_Also: InterruptibleTaskCondition */ final class TaskCondition : core.sync.condition.Condition { @safe: private TaskConditionImpl!(false, Mutex) m_impl; this(core.sync.mutex.Mutex mtx) { m_impl.setup(mtx); super(mtx); } override @property Mutex mutex() { return m_impl.mutex; } override void wait() { m_impl.wait(); } override bool wait(Duration timeout) { return m_impl.wait(timeout); } override void notify() { m_impl.notify(); } override void notifyAll() { m_impl.notifyAll(); } } /** This example shows the typical usage pattern using a `while` loop to make sure that the final condition is reached. */ unittest { import vibe.core.core; import vibe.core.log; __gshared Mutex mutex; __gshared TaskCondition condition; __gshared int workers_still_running = 0; // setup the task condition mutex = new Mutex; condition = new TaskCondition(mutex); logDebug("SETTING UP TASKS"); // start up the workers and count how many are running foreach (i; 0 .. 4) { workers_still_running++; runWorkerTask({ // simulate some work sleep(100.msecs); // notify the waiter that we're finished synchronized (mutex) { workers_still_running--; logDebug("DECREMENT %s", workers_still_running); } logDebug("NOTIFY"); condition.notify(); }); } logDebug("STARTING WAIT LOOP"); // wait until all tasks have decremented the counter back to zero synchronized (mutex) { while (workers_still_running > 0) { logDebug("STILL running %s", workers_still_running); condition.wait(); } } } /** Alternative to `TaskCondition` that supports interruption. This class supports the use of `vibe.core.task.Task.interrupt()` while waiting in the `wait()` method. See `TaskCondition` for an example. Notice: Note that it is generally not safe to use an `InterruptibleTaskCondition` together with an interruptible mutex type. See_Also: `TaskCondition` */ final class InterruptibleTaskCondition { @safe: private TaskConditionImpl!(true, Lockable) m_impl; this(core.sync.mutex.Mutex mtx) { m_impl.setup(mtx); } this(Lockable mtx) { m_impl.setup(mtx); } @property Lockable mutex() { return m_impl.mutex; } void wait() { m_impl.wait(); } bool wait(Duration timeout) { return m_impl.wait(timeout); } void notify() { m_impl.notify(); } void notifyAll() { m_impl.notifyAll(); } } /** A manually triggered single threaded cross-task event. Note: the ownership can be shared between multiple fibers of the same thread. */ struct LocalManualEvent { import core.thread : Thread; import vibe.internal.async : Waitable, asyncAwait, asyncAwaitUninterruptible, asyncAwaitAny; @safe: private { alias Waiter = ThreadLocalWaiter!false; Waiter m_waiter; } // thread destructor in vibe.core.core will decrement the ref. count package static EventID ms_threadEvent; private void initialize() { import vibe.internal.allocator : Mallocator, makeGCSafe; m_waiter = () @trusted { return Mallocator.instance.makeGCSafe!Waiter; } (); } this(this) { if (m_waiter) return m_waiter.addRef(); } ~this() { import vibe.internal.allocator : Mallocator, disposeGCSafe; if (m_waiter) { if (!m_waiter.releaseRef()) () @trusted { Mallocator.instance.disposeGCSafe(m_waiter); } (); } } bool opCast() const nothrow { return m_waiter !is null; } /// A counter that is increased with every emit() call int emitCount() const nothrow { return m_waiter.m_emitCount; } /// Emits the signal, waking up all owners of the signal. int emit() nothrow { assert(m_waiter !is null, "LocalManualEvent is not initialized - use createManualEvent()"); logTrace("unshared emit"); auto ec = m_waiter.m_emitCount++; m_waiter.emit(); return ec; } /// Emits the signal, waking up a single owners of the signal. int emitSingle() nothrow { assert(m_waiter !is null, "LocalManualEvent is not initialized - use createManualEvent()"); logTrace("unshared single emit"); auto ec = m_waiter.m_emitCount++; m_waiter.emitSingle(); return ec; } /** Acquires ownership and waits until the signal is emitted. Note that in order not to miss any emits it is necessary to use the overload taking an integer. Throws: May throw an $(D InterruptException) if the task gets interrupted using $(D Task.interrupt()). */ int wait() { return wait(this.emitCount); } /** Acquires ownership and waits until the emit count differs from the given one or until a timeout is reached. Throws: May throw an $(D InterruptException) if the task gets interrupted using $(D Task.interrupt()). */ int wait(int emit_count) { return doWait!true(Duration.max, emit_count); } /// ditto int wait(Duration timeout, int emit_count) { return doWait!true(timeout, emit_count); } /** Same as $(D wait), but defers throwing any $(D InterruptException). This method is annotated $(D nothrow) at the expense that it cannot be interrupted. */ int waitUninterruptible() nothrow { return waitUninterruptible(this.emitCount); } /// ditto int waitUninterruptible(int emit_count) nothrow { return doWait!false(Duration.max, emit_count); } /// ditto int waitUninterruptible(Duration timeout, int emit_count) nothrow { return doWait!false(timeout, emit_count); } private int doWait(bool interruptible)(Duration timeout, int emit_count) { import std.datetime : Clock, SysTime, UTC; assert(m_waiter !is null, "LocalManualEvent is not initialized - use createManualEvent()"); SysTime target_timeout, now; if (timeout != Duration.max) { try now = Clock.currTime(UTC()); catch (Exception e) { assert(false, e.msg); } target_timeout = now + timeout; } while (m_waiter.m_emitCount <= emit_count) { m_waiter.wait!interruptible(timeout != Duration.max ? target_timeout - now : Duration.max); try now = Clock.currTime(UTC()); catch (Exception e) { assert(false, e.msg); } if (now >= target_timeout) break; } return m_waiter.m_emitCount; } } unittest { import vibe.core.core : exitEventLoop, runEventLoop, runTask, sleep; auto e = createManualEvent(); auto w1 = runTask({ e.wait(100.msecs, e.emitCount); }); auto w2 = runTask({ e.wait(500.msecs, e.emitCount); }); runTask({ sleep(50.msecs); e.emit(); sleep(50.msecs); assert(!w1.running && !w2.running); exitEventLoop(); }); runEventLoop(); } unittest { // ensure that cancelled waiters are properly handled and that a FIFO order is implemented import vibe.core.core : exitEventLoop, runEventLoop, runTask, sleep; LocalManualEvent l = createManualEvent(); Task t2; runTask({ l.wait(); t2.interrupt(); sleep(20.msecs); exitEventLoop(); }); t2 = runTask({ try { l.wait(); assert(false, "Shouldn't reach this."); } catch (InterruptException e) {} }); runTask({ l.emit(); }); runEventLoop(); } unittest { // ensure that LocalManualEvent behaves correctly after being copied import vibe.core.core : exitEventLoop, runEventLoop, runTask, sleep; LocalManualEvent l = createManualEvent(); runTask({ auto lc = l; sleep(100.msecs); lc.emit(); }); runTask({ assert(l.wait(1.seconds, l.emitCount)); exitEventLoop(); }); runEventLoop(); } /** A manually triggered multi threaded cross-task event. Note: the ownership can be shared between multiple fibers and threads. */ struct ManualEvent { import core.thread : Thread; import vibe.internal.async : Waitable, asyncAwait, asyncAwaitUninterruptible, asyncAwaitAny; import vibe.internal.list : StackSList; @safe: private { alias ThreadWaiter = ThreadLocalWaiter!true; int m_emitCount; static struct Waiters { StackSList!ThreadWaiter active; // actively waiting StackSList!ThreadWaiter free; // free-list of reusable waiter structs } Monitor!(Waiters, shared(SpinLock)) m_waiters; } // thread destructor in vibe.core.core will decrement the ref. count package static EventID ms_threadEvent; enum EmitMode { single, all } @disable this(this); deprecated("ManualEvent is always non-null!") bool opCast() const shared nothrow { return true; } /// A counter that is increased with every emit() call int emitCount() const shared nothrow @trusted { return atomicLoad(m_emitCount); } /// Emits the signal, waking up all owners of the signal. int emit() shared nothrow @trusted { import core.atomic : atomicOp, cas; () @trusted { logTrace("emit shared %s", cast(void*)&this); } (); auto ec = atomicOp!"+="(m_emitCount, 1); auto thisthr = Thread.getThis(); ThreadWaiter lw; auto drv = eventDriver; m_waiters.lock.active.filter((ThreadWaiter w) { () @trusted { logTrace("waiter %s", cast(void*)w); } (); if (w.m_driver is drv) { lw = w; lw.addRef(); } else { try { assert(w.m_event != EventID.init); () @trusted { return cast(shared)w.m_driver; } ().events.trigger(w.m_event, true); } catch (Exception e) assert(false, e.msg); } return true; }); () @trusted { logTrace("lw %s", cast(void*)lw); } (); if (lw) { lw.emit(); releaseWaiter(lw); } logTrace("emit shared done"); return ec; } /// Emits the signal, waking up at least one waiting task int emitSingle() shared nothrow @trusted { import core.atomic : atomicOp, cas; () @trusted { logTrace("emit shared single %s", cast(void*)&this); } (); auto ec = atomicOp!"+="(m_emitCount, 1); auto thisthr = Thread.getThis(); ThreadWaiter lw; auto drv = eventDriver; m_waiters.lock.active.iterate((ThreadWaiter w) { () @trusted { logTrace("waiter %s", cast(void*)w); } (); if (w.unused) return true; if (w.m_driver is drv) { lw = w; lw.addRef(); } else { try { assert(w.m_event != EventID.invalid); () @trusted { return cast(shared)w.m_driver; } ().events.trigger(w.m_event, true); } catch (Exception e) assert(false, e.msg); } return false; }); () @trusted { logTrace("lw %s", cast(void*)lw); } (); if (lw) { lw.emitSingle(); releaseWaiter(lw); } logTrace("emit shared done"); return ec; } /** Acquires ownership and waits until the signal is emitted. Note that in order not to miss any emits it is necessary to use the overload taking an integer. Throws: May throw an $(D InterruptException) if the task gets interrupted using $(D Task.interrupt()). */ int wait() shared { return wait(this.emitCount); } /** Acquires ownership and waits until the emit count differs from the given one or until a timeout is reached. Throws: May throw an $(D InterruptException) if the task gets interrupted using $(D Task.interrupt()). */ int wait(int emit_count) shared { return doWaitShared!true(Duration.max, emit_count); } /// ditto int wait(Duration timeout, int emit_count) shared { return doWaitShared!true(timeout, emit_count); } /** Same as $(D wait), but defers throwing any $(D InterruptException). This method is annotated $(D nothrow) at the expense that it cannot be interrupted. */ int waitUninterruptible() shared nothrow { return waitUninterruptible(this.emitCount); } /// ditto int waitUninterruptible(int emit_count) shared nothrow { return doWaitShared!false(Duration.max, emit_count); } /// ditto int waitUninterruptible(Duration timeout, int emit_count) shared nothrow { return doWaitShared!false(timeout, emit_count); } private int doWaitShared(bool interruptible)(Duration timeout, int emit_count) shared { import std.datetime : SysTime, Clock, UTC; () @trusted { logTrace("wait shared %s", cast(void*)&this); } (); if (ms_threadEvent is EventID.invalid) { ms_threadEvent = eventDriver.events.create(); assert(ms_threadEvent != EventID.invalid, "Failed to create event!"); } SysTime target_timeout, now; if (timeout != Duration.max) { try now = Clock.currTime(UTC()); catch (Exception e) { assert(false, e.msg); } target_timeout = now + timeout; } int ec = this.emitCount; acquireThreadWaiter((scope ThreadWaiter w) { while (ec <= emit_count) { w.wait!interruptible(timeout != Duration.max ? target_timeout - now : Duration.max, ms_threadEvent, () => this.emitCount > emit_count); ec = this.emitCount; if (timeout != Duration.max) { try now = Clock.currTime(UTC()); catch (Exception e) { assert(false, e.msg); } if (now >= target_timeout) break; } } }); return ec; } private void acquireThreadWaiter(DEL)(scope DEL del) shared { import vibe.internal.allocator : processAllocator, makeGCSafe; ThreadWaiter w; auto drv = eventDriver; with (m_waiters.lock) { active.iterate((aw) { if (aw.m_driver is drv) { w = aw; w.addRef(); return false; } return true; }); if (!w) { free.filter((fw) { if (fw.m_driver is drv) { w = fw; w.addRef(); return false; } return true; }); if (!w) { () @trusted { try { w = processAllocator.makeGCSafe!ThreadWaiter; w.m_driver = drv; w.m_event = ms_threadEvent; } catch (Exception e) { assert(false, "Failed to allocate thread waiter."); } } (); } assert(w.m_refCount == 1); active.add(w); } } scope (exit) releaseWaiter(w); del(w); } private void releaseWaiter(ThreadWaiter w) shared nothrow { if (!w.releaseRef()) { assert(w.m_driver is eventDriver, "Waiter was reassigned a different driver!?"); assert(w.unused, "Waiter still used, but not referenced!?"); with (m_waiters.lock) { auto rmvd = active.remove(w); assert(rmvd, "Waiter not in active queue anymore!?"); free.add(w); // TODO: cap size of m_freeWaiters } } } } unittest { import vibe.core.core : exitEventLoop, runEventLoop, runTask, runWorkerTaskH, sleep; auto e = createSharedManualEvent(); auto w1 = runTask({ e.wait(100.msecs, e.emitCount); }); static void w(shared(ManualEvent)* e) { e.wait(500.msecs, e.emitCount); } auto w2 = runWorkerTaskH(&w, &e); runTask({ sleep(50.msecs); e.emit(); sleep(50.msecs); assert(!w1.running && !w2.running); exitEventLoop(); }); runEventLoop(); } unittest { import vibe.core.core : runTask, runWorkerTaskH, setTimer, sleep; import vibe.core.taskpool : TaskPool; import core.time : msecs, usecs; import std.concurrency : send, receiveOnly; import std.random : uniform; auto tpool = new shared TaskPool(4); scope (exit) tpool.terminate(); static void test(shared(ManualEvent)* evt, Task owner) { owner.tid.send(Task.getThis()); int ec = evt.emitCount; auto thist = Task.getThis(); auto tm = setTimer(500.msecs, { thist.interrupt(); }); // watchdog scope (exit) tm.stop(); while (ec < 5_000) { tm.rearm(500.msecs); sleep(uniform(0, 10_000).usecs); if (uniform(0, 10) == 0) evt.emit(); auto ecn = evt.wait(ec); assert(ecn > ec); ec = ecn; } } auto watchdog = setTimer(30.seconds, { assert(false, "ManualEvent test has hung."); }); scope (exit) watchdog.stop(); auto e = createSharedManualEvent(); Task[] tasks; runTask({ auto thist = Task.getThis(); // start 25 tasks in each thread foreach (i; 0 .. 25) tpool.runTaskDist(&test, &e, thist); // collect all task handles foreach (i; 0 .. 4*25) tasks ~= receiveOnly!Task; auto tm = setTimer(500.msecs, { thist.interrupt(); }); // watchdog scope (exit) tm.stop(); int pec = 0; while (e.emitCount < 5_000) { tm.rearm(500.msecs); sleep(50.usecs); e.emit(); } // wait for all worker tasks to finish foreach (t; tasks) t.join(); }).join(); } package shared struct Monitor(T, M) { alias Mutex = M; alias Data = T; private { Mutex mutex; Data data; } static struct Locked { shared(Monitor)* m; @disable this(this); ~this() { () @trusted { (cast(Mutex)m.mutex).unlock(); } (); } ref inout(Data) get() inout @trusted { return *cast(inout(Data)*)&m.data; } alias get this; } Locked lock() { () @trusted { (cast(Mutex)mutex).lock(); } (); return Locked(() @trusted { return &this; } ()); } const(Locked) lock() const { () @trusted { (cast(Mutex)mutex).lock(); } (); return const(Locked)(() @trusted { return &this; } ()); } } package shared(Monitor!(T, M)) createMonitor(T, M)(M mutex) @trusted { shared(Monitor!(T, M)) ret; ret.mutex = cast(shared)mutex; return ret; } package struct SpinLock { private shared int locked; static int threadID = 0; static void setup() { import core.thread : Thread; threadID = cast(int)cast(void*)Thread.getThis(); } @safe nothrow @nogc shared: bool tryLock() @trusted { assert(threadID != 0, "SpinLock.setup() was not called."); assert(atomicLoad(locked) != threadID, "Recursive lock attempt."); return cas(&locked, 0, threadID); } void lock() { while (!tryLock()) {} } void unlock() @trusted { assert(atomicLoad(locked) == threadID, "Unlocking spin lock that is not owned by the current thread."); atomicStore(locked, 0); } } private final class ThreadLocalWaiter(bool EVENT_TRIGGERED) { import vibe.internal.list : CircularDList; private { static struct TaskWaiter { TaskWaiter* prev, next; void delegate() @safe nothrow notifier; void wait(void delegate() @safe nothrow del) @safe nothrow { assert(notifier is null, "Local waiter is used twice!"); notifier = del; } void cancel() @safe nothrow { notifier = null; } void emit() @safe nothrow { auto n = notifier; notifier = null; n(); } } static if (EVENT_TRIGGERED) { package(vibe) ThreadLocalWaiter next; // queue of other waiters of the same thread NativeEventDriver m_driver; EventID m_event = EventID.invalid; } else { int m_emitCount = 0; } int m_refCount = 1; TaskWaiter m_pivot; TaskWaiter m_emitPivot; CircularDList!(TaskWaiter*) m_waiters; } this() { m_waiters = CircularDList!(TaskWaiter*)(() @trusted { return &m_pivot; } ()); } static if (EVENT_TRIGGERED) { ~this() { if (m_event != EventID.invalid) eventDriver.events.releaseRef(m_event); } } @property bool unused() const @safe nothrow { return m_waiters.empty; } void addRef() @safe nothrow { assert(m_refCount >= 0); m_refCount++; } bool releaseRef() @safe nothrow { assert(m_refCount > 0); return --m_refCount > 0; } bool wait(bool interruptible)(Duration timeout, EventID evt = EventID.invalid, scope bool delegate() @safe nothrow exit_condition = null) @safe { import std.datetime : SysTime, Clock, UTC; import vibe.internal.async : Waitable, asyncAwaitAny; TaskWaiter waiter_store; TaskWaiter* waiter = () @trusted { return &waiter_store; } (); m_waiters.insertBack(waiter); assert(waiter.next !is null); scope (exit) if (waiter.next !is null) { m_waiters.remove(waiter); assert(!waiter.next); } SysTime target_timeout, now; if (timeout != Duration.max) { try now = Clock.currTime(UTC()); catch (Exception e) { assert(false, e.msg); } target_timeout = now + timeout; } bool cancelled; alias waitable = Waitable!(typeof(TaskWaiter.notifier), (cb) { waiter.wait(cb); }, (cb) { cancelled = true; waiter.cancel(); }, () {} ); alias ewaitable = Waitable!(EventCallback, (cb) { eventDriver.events.wait(evt, cb); // check for exit condition *after* starting to wait for the event // to avoid a race condition if (exit_condition()) { eventDriver.events.cancelWait(evt, cb); cb(evt); } }, (cb) { eventDriver.events.cancelWait(evt, cb); }, (EventID) {} ); if (evt != EventID.invalid) { asyncAwaitAny!(interruptible, waitable, ewaitable)(timeout); } else { asyncAwaitAny!(interruptible, waitable)(timeout); } if (cancelled) { assert(waiter.next !is null, "Cancelled waiter not in queue anymore!?"); return false; } else { assert(waiter.next is null, "Triggered waiter still in queue!?"); return true; } } void emit() @safe nothrow { import std.algorithm.mutation : swap; import vibe.core.core : yield; if (m_waiters.empty) return; TaskWaiter* pivot = () @trusted { return &m_emitPivot; } (); if (pivot.next) { // another emit in progress? // shift pivot to the end, so that the other emit call will process all pending waiters if (pivot !is m_waiters.back) { m_waiters.remove(pivot); m_waiters.insertBack(pivot); } return; } m_waiters.insertBack(pivot); scope (exit) m_waiters.remove(pivot); foreach (w; m_waiters) { if (w is pivot) break; emitWaiter(w); } } bool emitSingle() @safe nothrow { if (m_waiters.empty) return false; TaskWaiter* pivot = () @trusted { return &m_emitPivot; } (); if (pivot.next) { // another emit in progress? // shift pivot to the right, so that the other emit call will process another waiter if (pivot !is m_waiters.back) { auto n = pivot.next; m_waiters.remove(pivot); m_waiters.insertAfter(pivot, n); } return true; } emitWaiter(m_waiters.front); return true; } private void emitWaiter(TaskWaiter* w) @safe nothrow { m_waiters.remove(w); if (w.notifier !is null) { logTrace("notify task %s %s %s", cast(void*)w, () @trusted { return cast(void*)w.notifier.funcptr; } (), w.notifier.ptr); w.emit(); } else logTrace("notify callback is null"); } } private struct TaskMutexImpl(bool INTERRUPTIBLE) { private { shared(bool) m_locked = false; shared(uint) m_waiters = 0; shared(ManualEvent) m_signal; debug Task m_owner; } void setup() { } @trusted bool tryLock() { if (cas(&m_locked, false, true)) { debug m_owner = Task.getThis(); debug(VibeMutexLog) logTrace("mutex %s lock %s", cast(void*)&this, atomicLoad(m_waiters)); return true; } return false; } @trusted void lock() { if (tryLock()) return; debug assert(m_owner == Task() || m_owner != Task.getThis(), "Recursive mutex lock."); atomicOp!"+="(m_waiters, 1); debug(VibeMutexLog) logTrace("mutex %s wait %s", cast(void*)&this, atomicLoad(m_waiters)); scope(exit) atomicOp!"-="(m_waiters, 1); auto ecnt = m_signal.emitCount(); while (!tryLock()) { static if (INTERRUPTIBLE) ecnt = m_signal.wait(ecnt); else ecnt = m_signal.waitUninterruptible(ecnt); } } @trusted void unlock() { assert(m_locked); debug { assert(m_owner == Task.getThis()); m_owner = Task(); } atomicStore!(MemoryOrder.rel)(m_locked, false); debug(VibeMutexLog) logTrace("mutex %s unlock %s", cast(void*)&this, atomicLoad(m_waiters)); if (atomicLoad(m_waiters) > 0) m_signal.emit(); } } private struct RecursiveTaskMutexImpl(bool INTERRUPTIBLE) { import std.stdio; private { core.sync.mutex.Mutex m_mutex; Task m_owner; size_t m_recCount = 0; shared(uint) m_waiters = 0; shared(ManualEvent) m_signal; @property bool m_locked() const { return m_recCount > 0; } } void setup() { m_mutex = new core.sync.mutex.Mutex; } @trusted bool tryLock() { auto self = Task.getThis(); return m_mutex.performLocked!({ if (!m_owner) { assert(m_recCount == 0); m_recCount = 1; m_owner = self; return true; } else if (m_owner == self) { m_recCount++; return true; } return false; }); } @trusted void lock() { if (tryLock()) return; atomicOp!"+="(m_waiters, 1); debug(VibeMutexLog) logTrace("mutex %s wait %s", cast(void*)&this, atomicLoad(m_waiters)); scope(exit) atomicOp!"-="(m_waiters, 1); auto ecnt = m_signal.emitCount(); while (!tryLock()) { static if (INTERRUPTIBLE) ecnt = m_signal.wait(ecnt); else ecnt = m_signal.waitUninterruptible(ecnt); } } @trusted void unlock() { auto self = Task.getThis(); m_mutex.performLocked!({ assert(m_owner == self); assert(m_recCount > 0); m_recCount--; if (m_recCount == 0) { m_owner = Task.init; } }); debug(VibeMutexLog) logTrace("mutex %s unlock %s", cast(void*)&this, atomicLoad(m_waiters)); if (atomicLoad(m_waiters) > 0) m_signal.emit(); } } private struct TaskConditionImpl(bool INTERRUPTIBLE, LOCKABLE) { private { LOCKABLE m_mutex; shared(ManualEvent) m_signal; } static if (is(LOCKABLE == Lockable)) { final class MutexWrapper : Lockable { private core.sync.mutex.Mutex m_mutex; this(core.sync.mutex.Mutex mtx) { m_mutex = mtx; } @trusted void lock() { m_mutex.lock(); } @trusted void unlock() { m_mutex.unlock(); } @trusted bool tryLock() { return m_mutex.tryLock(); } } void setup(core.sync.mutex.Mutex mtx) { setup(new MutexWrapper(mtx)); } } void setup(LOCKABLE mtx) { m_mutex = mtx; } @property LOCKABLE mutex() { return m_mutex; } @trusted void wait() { if (auto tm = cast(TaskMutex)m_mutex) { assert(tm.m_impl.m_locked); debug assert(tm.m_impl.m_owner == Task.getThis()); } auto refcount = m_signal.emitCount; m_mutex.unlock(); scope(exit) m_mutex.lock(); static if (INTERRUPTIBLE) m_signal.wait(refcount); else m_signal.waitUninterruptible(refcount); } @trusted bool wait(Duration timeout) { assert(!timeout.isNegative()); if (auto tm = cast(TaskMutex)m_mutex) { assert(tm.m_impl.m_locked); debug assert(tm.m_impl.m_owner == Task.getThis()); } auto refcount = m_signal.emitCount; m_mutex.unlock(); scope(exit) m_mutex.lock(); static if (INTERRUPTIBLE) return m_signal.wait(timeout, refcount) != refcount; else return m_signal.waitUninterruptible(timeout, refcount) != refcount; } @trusted void notify() { m_signal.emit(); } @trusted void notifyAll() { m_signal.emit(); } } /** Contains the shared state of a $(D TaskReadWriteMutex). * * Since a $(D TaskReadWriteMutex) consists of two actual Mutex * objects that rely on common memory, this class implements * the actual functionality of their method calls. * * The method implementations are based on two static parameters * ($(D INTERRUPTIBLE) and $(D INTENT)), which are configured through * template arguments: * * - $(D INTERRUPTIBLE) determines whether the mutex implementation * are interruptible by vibe.d's $(D vibe.core.task.Task.interrupt()) * method or not. * * - $(D INTENT) describes the intent, with which a locking operation is * performed (i.e. $(D READ_ONLY) or $(D READ_WRITE)). RO locking allows for * multiple Tasks holding the mutex, whereas RW locking will cause * a "bottleneck" so that only one Task can write to the protected * data at once. */ private struct ReadWriteMutexState(bool INTERRUPTIBLE) { /** The policy with which the mutex should operate. * * The policy determines how the acquisition of the locks is * performed and can be used to tune the mutex according to the * underlying algorithm in which it is used. * * According to the provided policy, the mutex will either favor * reading or writing tasks and could potentially starve the * respective opposite. * * cf. $(D core.sync.rwmutex.ReadWriteMutex.Policy) */ enum Policy : int { /** Readers are prioritized, writers may be starved as a result. */ PREFER_READERS = 0, /** Writers are prioritized, readers may be starved as a result. */ PREFER_WRITERS } /** The intent with which a locking operation is performed. * * Since both locks share the same underlying algorithms, the actual * intent with which a lock operation is performed (i.e read/write) * are passed as a template parameter to each method. */ enum LockingIntent : bool { /** Perform a read lock/unlock operation. Multiple reading locks can be * active at a time. */ READ_ONLY = 0, /** Perform a write lock/unlock operation. Only a single writer can * hold a lock at any given time. */ READ_WRITE = 1 } private { //Queue counters /** The number of reading tasks waiting for the lock to become available. */ shared(uint) m_waitingForReadLock = 0; /** The number of writing tasks waiting for the lock to become available. */ shared(uint) m_waitingForWriteLock = 0; //Lock counters /** The number of reading tasks that currently hold the lock. */ uint m_activeReadLocks = 0; /** The number of writing tasks that currently hold the lock (binary). */ ubyte m_activeWriteLocks = 0; /** The policy determining the lock's behavior. */ Policy m_policy; //Queue Events /** The event used to wake reading tasks waiting for the lock while it is blocked. */ shared(ManualEvent) m_readyForReadLock; /** The event used to wake writing tasks waiting for the lock while it is blocked. */ shared(ManualEvent) m_readyForWriteLock; /** The underlying mutex that gates the access to the shared state. */ Mutex m_counterMutex; } this(Policy policy) { m_policy = policy; m_counterMutex = new Mutex(); m_readyForReadLock = createSharedManualEvent(); m_readyForWriteLock = createSharedManualEvent(); } @disable this(this); /** The policy with which the lock has been created. */ @property policy() const { return m_policy; } version(RWMutexPrint) { /** Print out debug information during lock operations. */ void printInfo(string OP, LockingIntent INTENT)() nothrow { import std.string; try { import std.stdio; writefln("RWMutex: %s (%s), active: RO: %d, RW: %d; waiting: RO: %d, RW: %d", OP.leftJustify(10,' '), INTENT == LockingIntent.READ_ONLY ? "RO" : "RW", m_activeReadLocks, m_activeWriteLocks, m_waitingForReadLock, m_waitingForWriteLock ); } catch (Throwable t){} } } /** An internal shortcut method to determine the queue event for a given intent. */ @property ref auto queueEvent(LockingIntent INTENT)() { static if (INTENT == LockingIntent.READ_ONLY) return m_readyForReadLock; else return m_readyForWriteLock; } /** An internal shortcut method to determine the queue counter for a given intent. */ @property ref auto queueCounter(LockingIntent INTENT)() { static if (INTENT == LockingIntent.READ_ONLY) return m_waitingForReadLock; else return m_waitingForWriteLock; } /** An internal shortcut method to determine the current emitCount of the queue counter for a given intent. */ int emitCount(LockingIntent INTENT)() { return queueEvent!INTENT.emitCount(); } /** An internal shortcut method to determine the active counter for a given intent. */ @property ref auto activeCounter(LockingIntent INTENT)() { static if (INTENT == LockingIntent.READ_ONLY) return m_activeReadLocks; else return m_activeWriteLocks; } /** An internal shortcut method to wait for the queue event for a given intent. * * This method is used during the `lock()` operation, after a * `tryLock()` operation has been unsuccessfully finished. * The active fiber will yield and be suspended until the queue event * for the given intent will be fired. */ int wait(LockingIntent INTENT)(int count) { static if (INTERRUPTIBLE) return queueEvent!INTENT.wait(count); else return queueEvent!INTENT.waitUninterruptible(count); } /** An internal shortcut method to notify tasks waiting for the lock to become available again. * * This method is called whenever the number of owners of the mutex hits * zero; this is basically the counterpart to `wait()`. * It wakes any Task currently waiting for the mutex to be released. */ @trusted void notify(LockingIntent INTENT)() { static if (INTENT == LockingIntent.READ_ONLY) { //If the last reader unlocks the mutex, notify all waiting writers if (atomicLoad(m_waitingForWriteLock) > 0) m_readyForWriteLock.emit(); } else { //If a writer unlocks the mutex, notify both readers and writers if (atomicLoad(m_waitingForReadLock) > 0) m_readyForReadLock.emit(); if (atomicLoad(m_waitingForWriteLock) > 0) m_readyForWriteLock.emit(); } } /** An internal method that performs the acquisition attempt in different variations. * * Since both locks rely on a common TaskMutex object which gates the access * to their common data acquisition attempts for this lock are more complex * than for simple mutex variants. This method will thus be performing the * `tryLock()` operation in two variations, depending on the callee: * * If called from the outside ($(D WAIT_FOR_BLOCKING_MUTEX) = false), the method * will instantly fail if the underlying mutex is locked (i.e. during another * `tryLock()` or `unlock()` operation), in order to guarantee the fastest * possible locking attempt. * * If used internally by the `lock()` method ($(D WAIT_FOR_BLOCKING_MUTEX) = true), * the operation will wait for the mutex to be available before deciding if * the lock can be acquired, since the attempt would anyway be repeated until * it succeeds. This will prevent frequent retries under heavy loads and thus * should ensure better performance. */ @trusted bool tryLock(LockingIntent INTENT, bool WAIT_FOR_BLOCKING_MUTEX)() { //Log a debug statement for the attempt version(RWMutexPrint) printInfo!("tryLock",INTENT)(); //Try to acquire the lock static if (!WAIT_FOR_BLOCKING_MUTEX) { if (!m_counterMutex.tryLock()) return false; } else m_counterMutex.lock(); scope(exit) m_counterMutex.unlock(); //Log a debug statement for the attempt version(RWMutexPrint) printInfo!("checkCtrs",INTENT)(); //Check if there's already an active writer if (m_activeWriteLocks > 0) return false; //If writers are preferred over readers, check whether there //currently is a writer in the waiting queue and abort if //that's the case. static if (INTENT == LockingIntent.READ_ONLY) if (m_policy.PREFER_WRITERS && m_waitingForWriteLock > 0) return false; //If we are locking the mutex for writing, make sure that //there's no reader active. static if (INTENT == LockingIntent.READ_WRITE) if (m_activeReadLocks > 0) return false; //We can successfully acquire the lock! //Log a debug statement for the success. version(RWMutexPrint) printInfo!("lock",INTENT)(); //Increase the according counter //(number of active readers/writers) //and return a success code. activeCounter!INTENT += 1; return true; } /** Attempt to acquire the lock for a given intent. * * Returns: * `true`, if the lock was successfully acquired; * `false` otherwise. */ @trusted bool tryLock(LockingIntent INTENT)() { //Try to lock this mutex without waiting for the underlying //TaskMutex - fail if it is already blocked. return tryLock!(INTENT,false)(); } /** Acquire the lock for the given intent; yield and suspend until the lock has been acquired. */ @trusted void lock(LockingIntent INTENT)() { //Prepare a waiting action before the first //`tryLock()` call in order to avoid a race //condition that could lead to the queue notification //not being fired. auto count = emitCount!INTENT; atomicOp!"+="(queueCounter!INTENT,1); scope(exit) atomicOp!"-="(queueCounter!INTENT,1); //Try to lock the mutex auto locked = tryLock!(INTENT,true)(); if (locked) return; //Retry until we successfully acquired the lock while(!locked) { version(RWMutexPrint) printInfo!("wait",INTENT)(); count = wait!INTENT(count); locked = tryLock!(INTENT,true)(); } } /** Unlock the mutex after a successful acquisition. */ @trusted void unlock(LockingIntent INTENT)() { version(RWMutexPrint) printInfo!("unlock",INTENT)(); debug assert(activeCounter!INTENT > 0); synchronized(m_counterMutex) { //Decrement the counter of active lock holders. //If the counter hits zero, notify waiting Tasks activeCounter!INTENT -= 1; if (activeCounter!INTENT == 0) { version(RWMutexPrint) printInfo!("notify",INTENT)(); notify!INTENT(); } } } } /** A ReadWriteMutex implementation for fibers. * * This mutex can be used in exchange for a $(D core.sync.mutex.ReadWriteMutex), * but does not block the event loop in contention situations. The `reader` and `writer` * members are used for locking. Locking the `reader` mutex allows access to multiple * readers at once, while the `writer` mutex only allows a single writer to lock it at * any given time. Locks on `reader` and `writer` are mutually exclusive (i.e. whenever a * writer is active, no readers can be active at the same time, and vice versa). * * Notice: * Mutexes implemented by this class cannot be interrupted * using $(D vibe.core.task.Task.interrupt()). The corresponding * InterruptException will be deferred until the next blocking * operation yields the event loop. * * Use $(D InterruptibleTaskReadWriteMutex) as an alternative that can be * interrupted. * * cf. $(D core.sync.mutex.ReadWriteMutex) */ final class TaskReadWriteMutex { private { alias State = ReadWriteMutexState!false; alias LockingIntent = State.LockingIntent; alias READ_ONLY = LockingIntent.READ_ONLY; alias READ_WRITE = LockingIntent.READ_WRITE; /** The shared state used by the reader and writer mutexes. */ State m_state; } /** The policy with which the mutex should operate. * * The policy determines how the acquisition of the locks is * performed and can be used to tune the mutex according to the * underlying algorithm in which it is used. * * According to the provided policy, the mutex will either favor * reading or writing tasks and could potentially starve the * respective opposite. * * cf. $(D core.sync.rwmutex.ReadWriteMutex.Policy) */ alias Policy = State.Policy; /** A common baseclass for both of the provided mutexes. * * The intent for the according mutex is specified through the * $(D INTENT) template argument, which determines if a mutex is * used for read or write locking. */ final class Mutex(LockingIntent INTENT): core.sync.mutex.Mutex, Lockable { /** Try to lock the mutex. cf. $(D core.sync.mutex.Mutex) */ override bool tryLock() { return m_state.tryLock!INTENT(); } /** Lock the mutex. cf. $(D core.sync.mutex.Mutex) */ override void lock() { m_state.lock!INTENT(); } /** Unlock the mutex. cf. $(D core.sync.mutex.Mutex) */ override void unlock() { m_state.unlock!INTENT(); } } alias Reader = Mutex!READ_ONLY; alias Writer = Mutex!READ_WRITE; Reader reader; Writer writer; this(Policy policy = Policy.PREFER_WRITERS) { m_state = State(policy); reader = new Reader(); writer = new Writer(); } /** The policy with which the lock has been created. */ @property Policy policy() const { return m_state.policy; } } /** Alternative to $(D TaskReadWriteMutex) that supports interruption. * * This class supports the use of $(D vibe.core.task.Task.interrupt()) while * waiting in the `lock()` method. * * cf. $(D core.sync.mutex.ReadWriteMutex) */ final class InterruptibleTaskReadWriteMutex { @safe: private { alias State = ReadWriteMutexState!true; alias LockingIntent = State.LockingIntent; alias READ_ONLY = LockingIntent.READ_ONLY; alias READ_WRITE = LockingIntent.READ_WRITE; /** The shared state used by the reader and writer mutexes. */ State m_state; } /** The policy with which the mutex should operate. * * The policy determines how the acquisition of the locks is * performed and can be used to tune the mutex according to the * underlying algorithm in which it is used. * * According to the provided policy, the mutex will either favor * reading or writing tasks and could potentially starve the * respective opposite. * * cf. $(D core.sync.rwmutex.ReadWriteMutex.Policy) */ alias Policy = State.Policy; /** A common baseclass for both of the provided mutexes. * * The intent for the according mutex is specified through the * $(D INTENT) template argument, which determines if a mutex is * used for read or write locking. * */ final class Mutex(LockingIntent INTENT): core.sync.mutex.Mutex, Lockable { /** Try to lock the mutex. cf. $(D core.sync.mutex.Mutex) */ override bool tryLock() { return m_state.tryLock!INTENT(); } /** Lock the mutex. cf. $(D core.sync.mutex.Mutex) */ override void lock() { m_state.lock!INTENT(); } /** Unlock the mutex. cf. $(D core.sync.mutex.Mutex) */ override void unlock() { m_state.unlock!INTENT(); } } alias Reader = Mutex!READ_ONLY; alias Writer = Mutex!READ_WRITE; Reader reader; Writer writer; this(Policy policy = Policy.PREFER_WRITERS) { m_state = State(policy); reader = new Reader(); writer = new Writer(); } /** The policy with which the lock has been created. */ @property Policy policy() const { return m_state.policy; } }