-
Notifications
You must be signed in to change notification settings - Fork 284
/
core.d
1856 lines (1542 loc) · 50.8 KB
/
core.d
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 module contains the core functionality of the vibe.d framework.
Copyright: © 2012-2015 RejectedSoftware e.K.
License: Subject to the terms of the MIT license, as written in the included LICENSE.txt file.
Authors: Sönke Ludwig
*/
module vibe.core.core;
public import vibe.core.driver;
import vibe.core.args;
import vibe.core.concurrency;
import vibe.core.log;
import vibe.internal.newconcurrency;
import vibe.utils.array;
import std.algorithm;
import std.conv;
import std.encoding;
import core.exception;
import std.exception;
import std.functional;
import std.range : empty, front, popFront;
import std.string;
import std.variant;
import std.typecons : Typedef, Tuple, tuple;
import core.atomic;
import core.sync.condition;
import core.sync.mutex;
import core.stdc.stdlib;
import core.thread;
alias TaskEventCb = void function(TaskEvent, Task) nothrow;
version(Posix)
{
import core.sys.posix.signal;
import core.sys.posix.unistd;
import core.sys.posix.pwd;
static if (__traits(compiles, {import core.sys.posix.grp; getgrgid(0);})) {
import core.sys.posix.grp;
} else {
extern (C) {
struct group {
char* gr_name;
char* gr_passwd;
gid_t gr_gid;
char** gr_mem;
}
group* getgrgid(gid_t);
group* getgrnam(in char*);
}
}
}
version (Windows)
{
import core.stdc.signal;
}
/**************************************************************************************************/
/* Public functions */
/**************************************************************************************************/
/**
Starts the vibe event loop.
Note that this function is usually called automatically by the vibe framework. However, if
you provide your own main() function, you need to call it manually.
The event loop will continue running during the whole life time of the application.
Tasks will be started and handled from within the event loop.
*/
int runEventLoop()
{
logDebug("Starting event loop.");
s_eventLoopRunning = true;
scope (exit) {
s_eventLoopRunning = false;
s_exitEventLoop = false;
st_threadShutdownCondition.notifyAll();
}
// runs any yield()ed tasks first
assert(!s_exitEventLoop);
s_exitEventLoop = false;
driverCore.notifyIdle();
if (getExitFlag()) return 0;
// handle exit flag in the main thread to exit when
// exitEventLoop(true) is called from a thread)
if (Thread.getThis() is st_threads[0].thread)
runTask(toDelegate(&watchExitFlag));
if (auto err = getEventDriver().runEventLoop() != 0) {
if (err == 1) {
logDebug("No events active, exiting message loop.");
return 0;
}
logError("Error running event loop: %d", err);
return 1;
}
logDebug("Event loop done.");
return 0;
}
/**
Stops the currently running event loop.
Calling this function will cause the event loop to stop event processing and
the corresponding call to runEventLoop() will return to its caller.
Params:
shutdown_all_threads = If true, exits event loops of all threads -
false by default. Note that the event loops of all threads are
automatically stopped when the main thread exits, so usually
there is no need to set shutdown_all_threads to true.
*/
void exitEventLoop(bool shutdown_all_threads = false)
{
logDebug("exitEventLoop called (%s)", shutdown_all_threads);
assert(s_eventLoopRunning || shutdown_all_threads);
if (shutdown_all_threads) {
atomicStore(st_term, true);
st_threadsSignal.emit();
}
// shutdown the calling thread
s_exitEventLoop = true;
if (s_eventLoopRunning) getEventDriver().exitEventLoop();
}
/**
Process all pending events without blocking.
Checks if events are ready to trigger immediately, and run their callbacks if so.
Returns: Returns false $(I iff) exitEventLoop was called in the process.
*/
bool processEvents()
{
if (!getEventDriver().processEvents()) return false;
driverCore.notifyIdle();
return true;
}
/**
Sets a callback that is called whenever no events are left in the event queue.
The callback delegate is called whenever all events in the event queue have been
processed. Returning true from the callback will cause another idle event to
be triggered immediately after processing any events that have arrived in the
meantime. Returning false will instead wait until another event has arrived first.
*/
void setIdleHandler(void delegate() del)
{
s_idleHandler = { del(); return false; };
}
/// ditto
void setIdleHandler(bool delegate() del)
{
s_idleHandler = del;
}
/**
Runs a new asynchronous task.
task will be called synchronously from within the vibeRunTask call. It will
continue to run until vibeYield() or any of the I/O or wait functions is
called.
Note that the maximum size of all args must not exceed `maxTaskParameterSize`.
*/
Task runTask(ARGS...)(void delegate(ARGS) task, ARGS args)
{
auto tfi = makeTaskFuncInfo(task, args);
return runTask_internal(tfi);
}
private Task runTask_internal(ref TaskFuncInfo tfi)
@safe nothrow {
import std.typecons : Tuple, tuple;
CoreTask f;
while (!f && !s_availableFibers.empty) {
f = s_availableFibers.back;
s_availableFibers.popBack();
if (() @trusted nothrow { return f.state; } () != Fiber.State.HOLD) f = null;
}
if (f is null) {
// if there is no fiber available, create one.
if (s_availableFibers.capacity == 0) s_availableFibers.capacity = 1024;
logDebugV("Creating new fiber...");
s_fiberCount++;
f = new CoreTask;
}
f.m_taskFunc = tfi;
f.bumpTaskCounter();
auto handle = f.task();
debug Task self = Task.getThis();
debug if (s_taskEventCallback) {
if (self != Task.init) () @trusted { s_taskEventCallback(TaskEvent.yield, self); } ();
() @trusted { s_taskEventCallback(TaskEvent.preStart, handle); } ();
}
driverCore.resumeTask(handle, null, true);
debug if (s_taskEventCallback) {
() @trusted { s_taskEventCallback(TaskEvent.postStart, handle); } ();
if (self != Task.init) () @trusted { s_taskEventCallback(TaskEvent.resume, self); } ();
}
return handle;
}
/**
Runs a new asynchronous task in a worker thread.
Only function pointers with weakly isolated arguments are allowed to be
able to guarantee thread-safety.
*/
void runWorkerTask(FT, ARGS...)(FT func, auto ref ARGS args)
if (is(typeof(*func) == function))
{
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
runWorkerTask_unsafe(func, args);
}
/// ditto
void runWorkerTask(alias method, T, ARGS...)(shared(T) object, auto ref ARGS args)
if (is(typeof(__traits(getMember, object, __traits(identifier, method)))))
{
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
auto func = &__traits(getMember, object, __traits(identifier, method));
runWorkerTask_unsafe(func, args);
}
/**
Runs a new asynchronous task in a worker thread, returning the task handle.
This function will yield and wait for the new task to be created and started
in the worker thread, then resume and return it.
Only function pointers with weakly isolated arguments are allowed to be
able to guarantee thread-safety.
*/
Task runWorkerTaskH(FT, ARGS...)(FT func, auto ref ARGS args)
if (is(typeof(*func) == function))
{
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
alias PrivateTask = Typedef!(Task, Task.init, __PRETTY_FUNCTION__);
Task caller = Task.getThis();
// workaround for runWorkerTaskH to work when called outside of a task
if (caller == Task.init) {
Task ret;
runTask({ ret = runWorkerTaskH(func, args); }).join();
return ret;
}
assert(caller != Task.init, "runWorkderTaskH can currently only be called from within a task.");
static void taskFun(Task caller, FT func, ARGS args) {
PrivateTask callee = Task.getThis();
caller.prioritySendCompat(callee);
mixin(callWithMove!ARGS("func", "args"));
}
runWorkerTask_unsafe(&taskFun, caller, func, args);
return cast(Task)receiveOnlyCompat!PrivateTask();
}
/// ditto
Task runWorkerTaskH(alias method, T, ARGS...)(shared(T) object, auto ref ARGS args)
if (is(typeof(__traits(getMember, object, __traits(identifier, method)))))
{
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
auto func = &__traits(getMember, object, __traits(identifier, method));
alias FT = typeof(func);
alias PrivateTask = Typedef!(Task, Task.init, __PRETTY_FUNCTION__);
Task caller = Task.getThis();
// workaround for runWorkerTaskH to work when called outside of a task
if (caller == Task.init) {
Task ret;
runTask({ ret = runWorkerTaskH!method(object, args); }).join();
return ret;
}
assert(caller != Task.init, "runWorkderTaskH can currently only be called from within a task.");
static void taskFun(Task caller, FT func, ARGS args) {
PrivateTask callee = Task.getThis();
caller.prioritySendCompat(callee);
mixin(callWithMove!ARGS("func", "args"));
}
runWorkerTask_unsafe(&taskFun, caller, func, args);
return cast(Task)receiveOnlyCompat!PrivateTask();
}
/// Running a worker task using a function
unittest {
static void workerFunc(int param)
{
logInfo("Param: %s", param);
}
static void test()
{
runWorkerTask(&workerFunc, 42);
runWorkerTask(&workerFunc, cast(ubyte)42); // implicit conversion #719
runWorkerTaskDist(&workerFunc, 42);
runWorkerTaskDist(&workerFunc, cast(ubyte)42); // implicit conversion #719
}
}
/// Running a worker task using a class method
unittest {
static class Test {
void workerMethod(int param)
shared {
logInfo("Param: %s", param);
}
}
static void test()
{
auto cls = new shared Test;
runWorkerTask!(Test.workerMethod)(cls, 42);
runWorkerTask!(Test.workerMethod)(cls, cast(ubyte)42); // #719
runWorkerTaskDist!(Test.workerMethod)(cls, 42);
runWorkerTaskDist!(Test.workerMethod)(cls, cast(ubyte)42); // #719
}
}
/// Running a worker task using a function and communicating with it
unittest {
static void workerFunc(Task caller)
{
int counter = 10;
while (receiveOnlyCompat!string() == "ping" && --counter) {
logInfo("pong");
caller.sendCompat("pong");
}
caller.sendCompat("goodbye");
}
static void test()
{
Task callee = runWorkerTaskH(&workerFunc, Task.getThis);
do {
logInfo("ping");
callee.sendCompat("ping");
} while (receiveOnlyCompat!string() == "pong");
}
static void work719(int) {}
static void test719() { runWorkerTaskH(&work719, cast(ubyte)42); }
}
/// Running a worker task using a class method and communicating with it
unittest {
static class Test {
void workerMethod(Task caller) shared {
int counter = 10;
while (receiveOnlyCompat!string() == "ping" && --counter) {
logInfo("pong");
caller.sendCompat("pong");
}
caller.sendCompat("goodbye");
}
}
static void test()
{
auto cls = new shared Test;
Task callee = runWorkerTaskH!(Test.workerMethod)(cls, Task.getThis());
do {
logInfo("ping");
callee.sendCompat("ping");
} while (receiveOnlyCompat!string() == "pong");
}
static class Class719 {
void work(int) shared {}
}
static void test719() {
auto cls = new shared Class719;
runWorkerTaskH!(Class719.work)(cls, cast(ubyte)42);
}
}
unittest { // run and join worker task from outside of a task
__gshared int i = 0;
auto t = runWorkerTaskH({ sleep(5.msecs); i = 1; });
// FIXME: joining between threads not yet supported
//t.join();
//assert(i == 1);
}
private void runWorkerTask_unsafe(CALLABLE, ARGS...)(CALLABLE callable, ref ARGS args)
{
import std.traits : ParameterTypeTuple;
import vibe.internal.meta.traits : areConvertibleTo;
import vibe.internal.meta.typetuple;
alias FARGS = ParameterTypeTuple!CALLABLE;
static assert(areConvertibleTo!(Group!ARGS, Group!FARGS),
"Cannot convert arguments '"~ARGS.stringof~"' to function arguments '"~FARGS.stringof~"'.");
setupWorkerThreads();
auto tfi = makeTaskFuncInfo(callable, args);
synchronized (st_threadsMutex) st_workerTasks ~= tfi;
st_threadsSignal.emit();
}
/**
Runs a new asynchronous task in all worker threads concurrently.
This function is mainly useful for long-living tasks that distribute their
work across all CPU cores. Only function pointers with weakly isolated
arguments are allowed to be able to guarantee thread-safety.
The number of tasks started is guaranteed to be equal to
`workerThreadCount`.
*/
void runWorkerTaskDist(FT, ARGS...)(FT func, auto ref ARGS args)
if (is(typeof(*func) == function))
{
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
runWorkerTaskDist_unsafe(func, args);
}
/// ditto
void runWorkerTaskDist(alias method, T, ARGS...)(shared(T) object, ARGS args)
{
auto func = &__traits(getMember, object, __traits(identifier, method));
foreach (T; ARGS) static assert(isWeaklyIsolated!T, "Argument type "~T.stringof~" is not safe to pass between threads.");
runWorkerTaskDist_unsafe(func, args);
}
private void runWorkerTaskDist_unsafe(CALLABLE, ARGS...)(ref CALLABLE callable, ref ARGS args)
{
import std.traits : ParameterTypeTuple;
import vibe.internal.meta.traits : areConvertibleTo;
import vibe.internal.meta.typetuple;
alias FARGS = ParameterTypeTuple!CALLABLE;
static assert(areConvertibleTo!(Group!ARGS, Group!FARGS),
"Cannot convert arguments '"~ARGS.stringof~"' to function arguments '"~FARGS.stringof~"'.");
setupWorkerThreads();
auto tfi = makeTaskFuncInfo(callable, args);
synchronized (st_threadsMutex) {
foreach (ref ctx; st_threads)
if (ctx.isWorker)
ctx.taskQueue ~= tfi;
}
st_threadsSignal.emit();
}
private TaskFuncInfo makeTaskFuncInfo(CALLABLE, ARGS...)(ref CALLABLE callable, ref ARGS args)
{
import std.algorithm : move;
import std.traits : hasElaborateAssign;
struct TARGS { ARGS expand; }
static assert(CALLABLE.sizeof <= TaskFuncInfo.callable.length);
static assert(TARGS.sizeof <= maxTaskParameterSize,
"The arguments passed to run(Worker)Task must not exceed "~
maxTaskParameterSize.to!string~" bytes in total size.");
static void callDelegate(TaskFuncInfo* tfi) {
assert(tfi.func is &callDelegate);
// copy original call data to stack
CALLABLE c;
TARGS args;
move(*(cast(CALLABLE*)tfi.callable.ptr), c);
move(*(cast(TARGS*)tfi.args.ptr), args);
// reset the info
tfi.func = null;
// make the call
mixin(callWithMove!ARGS("c", "args.expand"));
}
TaskFuncInfo tfi;
tfi.func = &callDelegate;
static if (hasElaborateAssign!CALLABLE) tfi.initCallable!CALLABLE();
static if (hasElaborateAssign!TARGS) tfi.initArgs!TARGS();
() @trusted {
tfi.typedCallable!CALLABLE = callable;
foreach (i, A; ARGS) {
static if (needsMove!A) args[i].move(tfi.typedArgs!TARGS.expand[i]);
else tfi.typedArgs!TARGS.expand[i] = args[i];
}
} ();
return tfi;
}
import core.cpuid : threadsPerCPU;
/**
Sets up num worker threads.
This function gives explicit control over the number of worker threads.
Note, to have an effect the function must be called prior to related worker
tasks functions which set up the default number of worker threads
implicitly.
Params:
num = The number of worker threads to initialize. Defaults to
`logicalProcessorCount`.
See_also: `runWorkerTask`, `runWorkerTaskH`, `runWorkerTaskDist`
*/
public void setupWorkerThreads(uint num = logicalProcessorCount())
{
static bool s_workerThreadsStarted = false;
if (s_workerThreadsStarted) return;
s_workerThreadsStarted = true;
synchronized (st_threadsMutex) {
if (st_threads.any!(t => t.isWorker))
return;
foreach (i; 0 .. num) {
auto thr = new Thread(&workerThreadFunc);
thr.name = format("Vibe Task Worker #%s", i);
st_threads ~= ThreadContext(thr, true);
thr.start();
}
}
}
/**
Determines the number of logical processors in the system.
This number includes virtual cores on hyper-threading enabled CPUs.
*/
public @property uint logicalProcessorCount()
{
version (linux) {
static if (__VERSION__ >= 2067) import core.sys.linux.sys.sysinfo;
return get_nprocs();
} else version (OSX) {
int count;
size_t count_len = count.sizeof;
sysctlbyname("hw.logicalcpu", &count, &count_len, null, 0);
return cast(uint)count_len;
} else version (Windows) {
import core.sys.windows.windows;
SYSTEM_INFO sysinfo;
GetSystemInfo(&sysinfo);
return sysinfo.dwNumberOfProcessors;
} else static assert(false, "Unsupported OS!");
}
version (OSX) private extern(C) int sysctlbyname(const(char)* name, void* oldp, size_t* oldlen, void* newp, size_t newlen);
version (linux) static if (__VERSION__ <= 2066) private extern(C) int get_nprocs();
/**
Suspends the execution of the calling task to let other tasks and events be
handled.
Calling this function in short intervals is recommended if long CPU
computations are carried out by a task. It can also be used in conjunction
with Signals to implement cross-fiber events with no polling.
Throws:
May throw an `InterruptException` if `Task.interrupt()` gets called on
the calling task.
*/
void yield()
@safe {
// throw any deferred exceptions
driverCore.processDeferredExceptions();
auto t = CoreTask.getThis();
if (t && t !is CoreTask.ms_coreTask) {
assert(!t.m_queue, "Calling yield() when already yielded!?");
if (!t.m_queue)
s_yieldedTasks.insertBack(t);
scope (exit) assert(t.m_queue is null, "Task not removed from yielders queue after being resumed.");
rawYield();
} else {
// Let yielded tasks execute
() @trusted { driverCore.notifyIdle(); } ();
}
}
/**
Yields execution of this task until an event wakes it up again.
Beware that the task will starve if no event wakes it up.
*/
void rawYield()
@safe {
driverCore.yieldForEvent();
}
/**
Suspends the execution of the calling task for the specified amount of time.
Note that other tasks of the same thread will continue to run during the
wait time, in contrast to $(D core.thread.Thread.sleep), which shouldn't be
used in vibe.d applications.
*/
void sleep(Duration timeout)
{
assert(timeout >= 0.seconds, "Argument to sleep must not be negative.");
if (timeout <= 0.seconds) return;
auto tm = setTimer(timeout, null);
tm.wait();
}
///
unittest {
import vibe.core.core : sleep;
import vibe.core.log : logInfo;
import core.time : msecs;
void test()
{
logInfo("Sleeping for half a second...");
sleep(500.msecs);
logInfo("Done sleeping.");
}
}
/**
Returns a new armed timer.
Note that timers can only work if an event loop is running.
Params:
timeout = Determines the minimum amount of time that elapses before the timer fires.
callback = This delegate will be called when the timer fires
periodic = Speficies if the timer fires repeatedly or only once
Returns:
Returns a Timer object that can be used to identify and modify the timer.
See_also: createTimer
*/
Timer setTimer(Duration timeout, void delegate() callback, bool periodic = false)
{
auto tm = createTimer(callback);
tm.rearm(timeout, periodic);
return tm;
}
///
unittest {
void printTime()
{
import std.datetime;
logInfo("The time is: %s", Clock.currTime());
}
void test()
{
import vibe.core.core;
// start a periodic timer that prints the time every second
setTimer(1.seconds, toDelegate(&printTime), true);
}
}
/**
Creates a new timer without arming it.
See_also: setTimer
*/
Timer createTimer(void delegate() callback)
{
auto drv = getEventDriver();
return Timer(drv, drv.createTimer(callback));
}
/**
Creates an event to wait on an existing file descriptor.
The file descriptor usually needs to be a non-blocking socket for this to
work.
Params:
file_descriptor = The Posix file descriptor to watch
event_mask = Specifies which events will be listened for
Returns:
Returns a newly created FileDescriptorEvent associated with the given
file descriptor.
*/
FileDescriptorEvent createFileDescriptorEvent(int file_descriptor, FileDescriptorEvent.Trigger event_mask)
{
auto drv = getEventDriver();
return drv.createFileDescriptorEvent(file_descriptor, event_mask);
}
/**
Sets the stack size to use for tasks.
The default stack size is set to 512 KiB on 32-bit systems and to 16 MiB
on 64-bit systems, which is sufficient for most tasks. Tuning this value
can be used to reduce memory usage for large numbers of concurrent tasks
or to avoid stack overflows for applications with heavy stack use.
Note that this function must be called at initialization time, before any
task is started to have an effect.
Also note that the stack will initially not consume actual physical memory -
it just reserves virtual address space. Only once the stack gets actually
filled up with data will physical memory then be reserved page by page. This
means that the stack can safely be set to large sizes on 64-bit systems
without having to worry about memory usage.
*/
void setTaskStackSize(size_t sz)
{
s_taskStackSize = sz;
}
/**
The number of worker threads used for processing worker tasks.
Note that this function will cause the worker threads to be started,
if they haven't already.
See_also: `runWorkerTask`, `runWorkerTaskH`, `runWorkerTaskDist`,
`setupWorkerThreads`
*/
@property size_t workerThreadCount()
out(count) { assert(count > 0); }
body {
setupWorkerThreads();
return st_threads.count!(c => c.isWorker);
}
/**
Sets the effective user and group ID to the ones configured for privilege lowering.
This function is useful for services run as root to give up on the privileges that
they only need for initialization (such as listening on ports <= 1024 or opening
system log files).
*/
void lowerPrivileges(string uname, string gname)
{
if (!isRoot()) return;
if (uname != "" || gname != "") {
static bool tryParse(T)(string s, out T n)
{
import std.conv, std.ascii;
if (!isDigit(s[0])) return false;
n = parse!T(s);
return s.length==0;
}
int uid = -1, gid = -1;
if (uname != "" && !tryParse(uname, uid)) uid = getUID(uname);
if (gname != "" && !tryParse(gname, gid)) gid = getGID(gname);
setUID(uid, gid);
} else logWarn("Vibe was run as root, and no user/group has been specified for privilege lowering. Running with full permissions.");
}
// ditto
void lowerPrivileges()
{
lowerPrivileges(s_privilegeLoweringUserName, s_privilegeLoweringGroupName);
}
/**
Sets a callback that is invoked whenever a task changes its status.
This function is useful mostly for implementing debuggers that
analyze the life time of tasks, including task switches. Note that
the callback will only be called for debug builds.
*/
void setTaskEventCallback(TaskEventCb func)
{
debug s_taskEventCallback = func;
}
/**
A version string representing the current vibe version
*/
enum vibeVersionString = "0.7.28";
/**
The maximum combined size of all parameters passed to a task delegate
See_Also: runTask
*/
enum maxTaskParameterSize = 128;
/**
Represents a timer.
*/
struct Timer {
private {
EventDriver m_driver;
size_t m_id;
debug uint m_magicNumber = 0x4d34f916;
}
private this(EventDriver driver, size_t id)
{
m_driver = driver;
m_id = id;
}
this(this)
{
debug assert(m_magicNumber == 0x4d34f916);
if (m_driver) m_driver.acquireTimer(m_id);
}
~this()
{
debug assert(m_magicNumber == 0x4d34f916);
if (m_driver && driverCore) m_driver.releaseTimer(m_id);
}
/// True if the timer is yet to fire.
@property bool pending() { return m_driver.isTimerPending(m_id); }
/// The internal ID of the timer.
@property size_t id() const { return m_id; }
bool opCast() const { return m_driver !is null; }
/** Resets the timer to the specified timeout
*/
void rearm(Duration dur, bool periodic = false)
in { assert(dur > 0.seconds); }
body { m_driver.rearmTimer(m_id, dur, periodic); }
/** Resets the timer and avoids any firing.
*/
void stop() { m_driver.stopTimer(m_id); }
/** Waits until the timer fires.
*/
void wait() { m_driver.waitTimer(m_id); }
}
/**
Implements a task local storage variable.
Task local variables, similar to thread local variables, exist separately
in each task. Consequently, they do not need any form of synchronization
when accessing them.
Note, however, that each TaskLocal variable will increase the memory footprint
of any task that uses task local storage. There is also an overhead to access
TaskLocal variables, higher than for thread local variables, but generelly
still O(1) (since actual storage acquisition is done lazily the first access
can require a memory allocation with unknown computational costs).
Notice:
FiberLocal instances MUST be declared as static/global thread-local
variables. Defining them as a temporary/stack variable will cause
crashes or data corruption!
Examples:
---
TaskLocal!string s_myString = "world";
void taskFunc()
{
assert(s_myString == "world");
s_myString = "hello";
assert(s_myString == "hello");
}
shared static this()
{
// both tasks will get independent storage for s_myString
runTask(&taskFunc);
runTask(&taskFunc);
}
---
*/
struct TaskLocal(T)
{
private {
size_t m_offset = size_t.max;
size_t m_id;
T m_initValue;
bool m_hasInitValue = false;
}
this(T init_val) { m_initValue = init_val; m_hasInitValue = true; }
@disable this(this);
void opAssign(T value) { this.storage = value; }
@property ref T storage()
{
auto fiber = CoreTask.getThis();
// lazily register in FLS storage
if (m_offset == size_t.max) {
static assert(T.alignof <= 8, "Unsupported alignment for type "~T.stringof);
assert(CoreTask.ms_flsFill % 8 == 0, "Misaligned fiber local storage pool.");
m_offset = CoreTask.ms_flsFill;
m_id = CoreTask.ms_flsCounter++;
CoreTask.ms_flsFill += T.sizeof;
while (CoreTask.ms_flsFill % 8 != 0)
CoreTask.ms_flsFill++;
}
// make sure the current fiber has enough FLS storage
if (fiber.m_fls.length < CoreTask.ms_flsFill) {
fiber.m_fls.length = CoreTask.ms_flsFill + 128;
fiber.m_flsInit.length = CoreTask.ms_flsCounter + 64;
}
// return (possibly default initialized) value
auto data = fiber.m_fls.ptr[m_offset .. m_offset+T.sizeof];
if (!fiber.m_flsInit[m_id]) {
fiber.m_flsInit[m_id] = true;
import std.traits : hasElaborateDestructor, hasAliasing;
static if (hasElaborateDestructor!T || hasAliasing!T) {
void function(void[], size_t) destructor = (void[] fls, size_t offset){
static if (hasElaborateDestructor!T) {
auto obj = cast(T*)&fls[offset];
// call the destructor on the object if a custom one is known declared
obj.destroy();
}
else static if (hasAliasing!T) {
// zero the memory to avoid false pointers
foreach (size_t i; offset .. offset + T.sizeof) {
ubyte* u = cast(ubyte*)&fls[i];
*u = 0;
}
}
};
FLSInfo fls_info;
fls_info.fct = destructor;
fls_info.offset = m_offset;
// make sure flsInfo has enough space
if (fiber.ms_flsInfo.length <= m_id)
fiber.ms_flsInfo.length = m_id + 64;
fiber.ms_flsInfo[m_id] = fls_info;
}
if (m_hasInitValue) {
static if (__traits(compiles, emplace!T(data, m_initValue)))
emplace!T(data, m_initValue);
else assert(false, "Cannot emplace initialization value for type "~T.stringof);
} else emplace!T(data);
}
return (cast(T[])data)[0];
}
alias storage this;
}
private struct FLSInfo {
void function(void[], size_t) fct;
size_t offset;
void destroy(void[] fls) {
fct(fls, offset);
}
}
/**
High level state change events for a Task
*/
enum TaskEvent {
preStart, /// Just about to invoke the fiber which starts execution
postStart, /// After the fiber has returned for the first time (by yield or exit)
start, /// Just about to start execution
yield, /// Temporarily paused