-
Notifications
You must be signed in to change notification settings - Fork 316
/
bdlmt_eventscheduler.h
2029 lines (1796 loc) · 89.5 KB
/
bdlmt_eventscheduler.h
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
// bdlmt_eventscheduler.h -*-C++-*-
// ----------------------------------------------------------------------------
// NOTICE
//
// This component is not up to date with current BDE coding standards, and
// should not be used as an example for new development.
// ----------------------------------------------------------------------------
#ifndef INCLUDED_BDLMT_EVENTSCHEDULER
#define INCLUDED_BDLMT_EVENTSCHEDULER
#include <bsls_ident.h>
BSLS_IDENT("$Id: $")
//@PURPOSE: Provide a thread-safe recurring and one-time event scheduler.
//
//@CLASSES:
// bdlmt::EventScheduler: a thread-safe event scheduler
// bdlmt::EventSchedulerEventHandle: handle to a single scheduled event
// bdlmt::EventSchedulerRecurringEventHandle: handle to a recurring event
// bdlmt::EventSchedulerTestTimeSource: class for testing time changes
//
//@SEE_ALSO: bdlmt_timereventscheduler
//
//@DESCRIPTION: This component provides a thread-safe event scheduler.
// 'bdlmt::EventScheduler', that implements methods to schedule and cancel
// recurring and one-time events. All of the callbacks for these events are
// processed by a separate thread (called the dispatcher thread). By default
// the callbacks are also executed in the dispatcher thread, but that behavior
// can be altered by providing a dispatcher functor at creation time (see the
// section {The Dispatcher Thread and the Dispatcher Functor}).
//
// Events may be referred to by 'bdlmt::EventSchedulerEventHandle' and
// 'bdlmt::EventSchedulerRecurringEventHandle' objects, which clean up after
// themselves when they go out of scope, or by 'Event' and 'RecurringEvent'
// pointers, which must be released using 'releaseEventRaw'. Such pointers are
// used in the "Raw" API of this class and must be used carefully. Note that
// the Handle objects have an implicit conversion to the corresponding 'Event'
// or 'RecurringEvent' pointer types, effectively providing extra overloads for
// methods that take a 'const Event*' to also take a 'const EventHandle&'.
//
///Comparison to 'bdlmt::TimerEventScheduler'
/// - - - - - - - - - - - - - - - - - - - - -
// This component was written after 'bdlmt_timereventscheduler', which suffered
// from a couple of short-comings: 1) there was a maximum number of events it
// could manage, and 2) it was inefficient at dealing with large numbers of
// events. This component addresses both those problems -- there is no limit
// on the number of events it can manage, and it is more efficient at dealing
// with large numbers of events. The disadvantage of this component relative
// to 'bdlmt_timereventscheduler' is that handles referring to managed events
// in a 'bdlmt::EventScheduler' are reference-counted and need to be released,
// while handles of events in a 'bdlmt::TimerEventScheduler' are integral types
// that do not need to be released.
//
///Thread Safety and "Raw" Event Pointers
///--------------------------------------
// 'bdlmt::EventScheduler' is thread-safe and thread-enabled, meaning that
// multiple threads may use their own instances of the class or use a shared
// instance without further synchronization. The thread safety and correct
// behavior of the component depend on the correct usage of 'Event' pointers,
// which refer to scheduled events in the "Raw" API of this class. In
// particular:
//..
// * Every 'Event*' and 'RecurringEvent*' populated by 'scheduleEventRaw'
// and 'scheduleRecurringEventRaw' must be released using 'releaseEventRaw.'
// - Pointers are not released automatically when events are completed.
// - Pointers are not released automatically when events are canceled.
// - Events are not canceled when pointers to them are released.
// * Pointers must not be used after being released.
// * Pointers must never be shared or duplicated without using
// 'addEventRefRaw' and 'addRecurringEventRefRaw' to get additional
// references; *each* such added reference must be released separately.
//..
// 'bdlmt::EventSchedulerEventHandle' and
// 'bdlmt::EventSchedulerRecurringEventHandle' are *const* *thread-safe*. It
// is not safe for multiple threads to invoke non-'const' methods on the same
// 'EventHandle' or 'RecurringEventHandle' object concurrently.
//
///The Dispatcher Thread and the Dispatcher Functor
///------------------------------------------------
// The scheduler creates a single separate thread (called the *dispatcher*
// *thread*) to process all the callbacks. The dispatcher thread executes the
// callbacks by passing them to the dispatcher functor (optionally specified at
// creation time). The default dispatcher functor simply invokes the passed
// callback, effectively executing it in the dispatcher thread. Users can
// alter this behavior by defining their own dispatcher functor (for example in
// order to use a thread pool or a separate thread to run the callbacks). Note
// that the user-supplied functor will still be run in the dispatcher thread.
//
// CAVEAT: Using a dispatcher functor such as the example above (to execute the
// callback in a separate thread) violates the guarantees of
// cancelEventAndWait(). Users who specify a dispatcher functor that transfers
// the event to another thread for execution should not use
// cancelEventAndWait(), and should instead ensure that the lifetime of any
// object bound to an event exceeds the lifetime of the mechanism used by the
// customized dispatcher functor.
//
///Timer Resolution and Order of Execution
///---------------------------------------
// It is intended that recurring and one-time events are processed as closely
// as possible to their respective time values, and that they are processed in
// the order scheduled. However, this component *guarantees* only that events
// will not be executed before their scheduled time. Generally, events that
// are scheduled more than 1 microsecond apart will be executed in the order
// scheduled; but different behavior may be observed when events are submitted
// after (or shortly before) their scheduled time.
//
// When events are executed in the dispatcher thread and take longer to
// complete than the time between events, the dispatcher can fall behind. In
// this case, events will be executed in the correct order as soon as the
// dispatcher thread becomes available; once the backlog is worked off, events
// will be executed at or near their scheduled times.
//
///Supported Clock Types
///---------------------
// An 'EventScheduler' optionally accepts a clock type at construction
// indicating the clock by which it will internally schedule events. The clock
// type may be indicated by either a 'bsls::SystemClockType::Enum' value, a
// 'bsl::chrono::system_clock' object (which is equivalent to specifying
// 'e_REALTIME'), or a 'bsl::chrono::steady_clock' object (equivalent to
// specifying 'e_MONOTONIC'). If a clock type is not specified, 'e_REALTIME'
// is used.
//
///Scheduling Using a 'bsl::chrono::time_point'
/// - - - - - - - - - - - - - - - - - - - - - -
// When creating either a one-time or recurring event, clients may pass a
// 'bsl::chrono::time_point' indicating the time the event should occur. This
// 'time_point' object can be associated with an arbitrary clock. If the
// 'time_point' is associated with a different clock than was indicated at
// construction of the event scheduler, those time points are converted to be
// relative to the event scheduler's clock for processing. A possible
// implementation of such a conversion would be:
//..
// bsls::TimeInterval(time - CLOCK::now()) + eventScheduler.now()
//..
// where 'time' is a 'time_point', 'CLOCK' is the clock associated with 'time',
// and 'eventScheduler' is the 'EventScheduler' on which the event is being
// scheduled. Notice that the conversion adds some imprecision and overhead to
// evaluation of the event. An event scheduler guarantees an event will occur
// at or after the supplied 'time_point', even if that 'time_point' is defined
// in terms of a 'CLOCK' different from the one used by the event scheduler.
// If there is a discontinuity between the clock for a 'time_point' and the
// event scheduler's clock, additional processing overhead may result (because
// the event may need to be rescheduled), and the event may also occur later
// than what one might otherwise expect.
//
///Scheduling Using a 'bsls::TimeInterval'
///- - - - - - - - - - - - - - - - - - - -
// When creating either a one-time or recurring event, clients may pass a
// 'bsls::TimeInterval' indicating the time the event should occur as an offset
// from an epoch. If the clock type indicated at construction is
// 'bsls::SystemClockType::e_REALTIME', time should be expressed as an absolute
// offset since 00:00:00 UTC, January 1, 1970 (which matches the epoch used in
// 'bdlt::CurrentTime::now(bsls::SystemClockType::e_REALTIME)', and
// 'bsl::chrono::system_clock::now()'). If the clock type indicated at
// construction is 'bsls::SystemClockType::e_MONOTONIC', time should be
// expressed as an absolute offset since the epoch of this clock (which matches
// the epoch used in
// 'bdlt::CurrentTime::now(bsls::SystemClockType::e_MONOTONIC)' and
// 'bsl::chrono::steady_clock').
//
///Event Clock Substitution
///------------------------
// For testing purposes, a class 'bdlmt::EventSchedulerTestTimeSource' is
// provided to allow manual manipulation of the system-time observed by a
// 'bdlmt::EventScheduler'. A test driver that interacts with a
// 'bdlmt::EventScheduler' can use a 'bdlmt::EventSchedulerTestTimeSource'
// object to control when scheduled events are triggered, allowing more
// reliable tests.
//
// A 'bdlmt::EventSchedulerTestTimeSource' can be constructed for any existing
// 'bdlmt::EventScheduler' object that has not been started and has not had any
// events scheduled. When the 'bdlmt::EventSchedulerTestTimeSource' is
// constructed, it will replace the clock of the 'bdlmt::EventScheduler' to
// which it is attached. The internal clock of the
// 'bdlmt::EventSchedulerTestTimeSource' will be initialized with an arbitrary
// value on construction, and will advance only when explicitly instructed to
// do so by a call to 'bdlt::EventSchedulerTestTimeSource::advanceTime'. The
// current value of the internal clock can be accessed by calling
// 'bdlt::EventSchedulerTestTimeSource::now', or 'bdlmt::EventScheduler::now'
// on the instance supplied to the 'bdlmt::EventSchedulerTestTimeSource'.
//
// Note that the initial value of 'bdlt::EventSchedulerTestTimeSource::now' is
// intentionally not synchronized with 'bsls::SystemTime::nowRealtimeClock'.
// All test events scheduled for a 'bdlmt::EventScheduler' that is instrumented
// with a 'bdlt::EventSchedulerTestTimeSource' should be scheduled in terms of
// an offset from whatever arbitrary time is reported by
// 'bdlt::EventSchedulerTestTimeSource'. See Example 3 below for an
// illustration of how this is done.
//
///Thread Name for Dispatcher Thread
///---------------------------------
// To facilitate debugging, users can provide a thread name as the 'threadName'
// attribute of the 'bslmt::ThreadAttributes' argument passed to the 'start'
// method, that will be used for the dispatcher thread. The thread name should
// not be used programmatically, but will appear in debugging tools on
// platforms that support naming threads to help users identify the source and
// purpose of a thread. If no 'ThreadAttributes' object is passed, or if the
// 'threadName' attribute is not set, the default value "bdl.EventSched" will
// be used.
//
///Usage
///-----
// This section illustrates intended use of this component.
//
///Example 1: Simple Clock
///- - - - - - - - - - - -
// In this example we wish to log some statistics periodically. We define a
// method to store the value of a variable into an array, and set up a
// scheduler to call that as a recurring event.
//..
// bsls::AtomicInt g_data; // Some global data we want to track
// typedef pair<bsls::TimeInterval, int> Value;
//
// void saveData(vector<Value> *array)
// {
// array->push_back(Value(bsls::SystemTime::nowRealtimeClock(), g_data));
// }
//..
// We allow the scheduler to run for a short time while changing this value and
// observe that the callback is executed:
//..
// bdlmt::EventScheduler scheduler;
// vector<Value> values;
//
// scheduler.scheduleRecurringEvent(bsls::TimeInterval(1.5),
// bdlf::BindUtil::bind(&saveData, &values)));
// scheduler.start();
// bsls::TimeInterval start = bsls::SystemTime::nowRealtimeClock();
// while ((bsls::SystemTime::nowRealtimeClock() -
// start).totalSecondsAsDouble() < 7) {
// ++g_data;
// }
// scheduler.stop();
// assert(values.size() >= 4);
// for (int i = 0; i < (int) values.size(); ++i) {
// cout << "At " << bdlt::EpochUtil::convertFromTimeInterval(
// values[i].first) <<
// " g_data was " << values[i].second << endl;
// }
//..
// This will display, e.g.:
//..
// At 26OCT2020_23:51:51.097283 g_data was 8008406
// At 26OCT2020_23:51:52.597287 g_data was 16723918
// At 26OCT2020_23:51:54.097269 g_data was 24563722
// At 26OCT2020_23:51:55.597262 g_data was 30291748
//..
//
///Example 2: Server Timeouts
/// - - - - - - - - - - - - -
// The following example shows how to use a 'bdlmt::EventScheduler' to
// implement a timeout mechanism in a server. 'my_Session' maintains several
// connections. It closes a connection if the data for it does not arrive
// before a timeout (specified at the server creation time).
//
// Because the timeout is relative to the arrival of data, it is best to use a
// "monotonic" clock that advances at a steady rate, rather than a "wall" clock
// that may fluctuate to reflect real time adjustments.
//..
// class my_Session{
// // This class encapsulates the data and state associated with a
// // connection and provides a method 'processData' to process the
// // incoming data for the connection.
// public:
// int processData(void *data, int length);
// // Process the specified 'data' of the specified 'length'. (TBD)
// };
//
// class my_Server {
// // This class implements a server maintaining several connections.
// // A connection is closed if the data for it does not arrive
// // before a timeout (specified at the server creation time).
//
// struct Connection {
// bdlmt::EventSchedulerEventHandle d_timerId; // handle for timeout
// // event
//
// my_Session *d_session_p; // session for this
// // connection
// };
//
// bsl::vector<Connection*> d_connections; // maintained connections
// bdlmt::EventScheduler d_scheduler; // timeout event scheduler
// bsls::TimeInterval d_ioTimeout; // time out
//
// void newConnection(Connection *connection);
// // Add the specified 'connection' to this server and schedule
// // the timeout event that closes this connection if the data
// // for this connection does not arrive before the timeout.
//
// void closeConnection(Connection *connection);
// // Close the specified 'connection' and remove it from this server.
//
// void dataAvailable(Connection *connection, void *data, int length);
// // Return if the specified 'connection' has already timed-out.
// // If not, cancel the existing timeout event for the 'connection',
// // process the specified 'data' of the specified 'length' and
// // schedule a new timeout event that closes the 'connection' if
// // the data does not arrive before the timeout.
//
// public:
// my_Server(const bsls::TimeInterval& ioTimeout,
// bslma::Allocator *allocator = 0);
// // Create a 'my_Server' object with a timeout value of
// // 'ioTimeout' seconds. Optionally specify a 'allocator' used to
// // supply memory. If 'allocator' is 0, the currently installed
// // default allocator is used.
//
// ~my_Server();
// // Perform the required clean-up and destroy this object.
// };
//
// my_Server::my_Server(const bsls::TimeInterval& ioTimeout,
// bslma::Allocator *alloc)
// : d_connections(alloc)
// , d_scheduler(bsls::SystemClockType::e_MONOTONIC, alloc)
// , d_ioTimeout(ioTimeout)
// {
// // TBD: logic to start monitoring the arriving connections or data
//
// d_scheduler.start();
// }
//
// my_Server::~my_Server()
// {
// // TBD: logic to clean up
//
// d_scheduler.stop();
// }
//
// void my_Server::newConnection(my_Server::Connection *connection)
// {
// // TBD: logic to add 'connection' to 'd_connections'
//
// // setup the timeout for data arrival
// d_scheduler.scheduleEvent(
// &connection->d_timerId,
// d_scheduler.now() + d_ioTimeout,
// bdlf::BindUtil::bind(&my_Server::closeConnection, this, connection));
// }
//
// void my_Server::closeConnection(my_Server::Connection *connection)
// {
// // TBD: logic to close the 'connection' and remove it from 'd_ioTimeout'
// }
//
// void my_Server::dataAvailable(my_Server::Connection *connection,
// void *data,
// int length)
// {
// // If connection has already timed out and closed, simply return.
// if (d_scheduler.cancelEvent(connection->d_timerId)) {
// return; // RETURN
// }
//
// // process the data
// connection->d_session_p->processData(data, length);
//
// // setup the timeout for data arrival
// d_scheduler.scheduleEvent(
// &connection->d_timerId,
// d_scheduler.now() + d_ioTimeout,
// bdlf::BindUtil::bind(&my_Server::closeConnection, this, connection));
// }
//..
//
///Example 3: Using the Test Time Source
///- - - - - - - - - - - - - - - - - - -
// For testing purposes, the class 'bdlmt::EventSchedulerTestTimeSource' is
// provided to allow a test to manipulate the system-time observed by a
// 'bdlmt::EventScheduler' in order to control when events are triggered.
// After a scheduler is constructed, a 'bdlmt::EventSchedulerTestTimeSource'
// object can be created atop the scheduler. A test can then use the test
// time-source to advance the scheduler's observed system-time in order to
// dispatch events in a manner coordinated by the test. Note that a
// 'bdlmt::EventSchedulerTestTimeSource' *must* be created on an
// event-scheduler before any events are scheduled, or the event-scheduler is
// started.
//
// This example shows how the clock may be altered:
//
//..
// void myCallbackFunction() {
// puts("Event triggered!");
// }
//
// void testCase() {
// // Create the scheduler
// bdlmt::EventScheduler scheduler;
//
// // Create the time-source.
// // Install the time-source in the scheduler.
// bdlmt::EventSchedulerTestTimeSource timeSource(&scheduler);
//
// // Retrieve the initial time held in the time-source.
// bsls::TimeInterval initialAbsoluteTime = timeSource.now();
//
// // Schedule a single-run event at a 35s offset.
// scheduler.scheduleEvent(initialAbsoluteTime + 35,
// bsl::function<void()>(&myCallbackFunction));
//
// // Schedule a 30s recurring event.
// scheduler.scheduleRecurringEvent(bsls::TimeInterval(30),
// bsl::function<void()>(
// &myCallbackFunction));
//
// // Start the dispatcher thread.
// scheduler.start();
//
// // Advance the time by 40 seconds so that each
// // event will run once.
// timeSource.advanceTime(bsls::TimeInterval(40));
//
// // The line "Event triggered!" should now have
// // been printed to the console twice.
//
// scheduler.stop();
// }
//..
//
// Note that this feature should be used only for testing purposes, never in
// production code.
#include <bdlscm_version.h>
#include <bdlcc_skiplist.h>
#include <bdlf_bind.h>
#include <bdlf_placeholder.h>
#include <bslma_allocator.h>
#include <bslma_usesbslmaallocator.h>
#include <bslmf_allocatorargt.h>
#include <bslmf_nestedtraitdeclaration.h>
#include <bslmt_condition.h>
#include <bslmt_lockguard.h>
#include <bslmt_mutex.h>
#include <bslmt_threadattributes.h>
#include <bslmt_threadutil.h>
#include <bsls_assert.h>
#include <bsls_atomic.h>
#include <bsls_libraryfeatures.h>
#include <bsls_review.h>
#include <bsls_systemclocktype.h>
#include <bsls_timeinterval.h>
#include <bsls_types.h>
#include <bsl_functional.h>
#include <bsl_memory.h>
#include <bsl_utility.h>
#ifdef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY
#include <bslmt_chronoutil.h>
#include <bsl_chrono.h>
#endif
namespace BloombergLP {
namespace bdlmt {
class EventSchedulerEventHandle;
class EventSchedulerRecurringEventHandle;
class EventSchedulerTestTimeSource_Data;
// ====================
// class EventScheduler
// ====================
class EventScheduler {
// This class provides a thread-safe event scheduler that executes
// callbacks in a separate "dispatcher thread." 'start' must be invoked to
// start dispatching the callbacks. 'stop' pauses the dispatching of the
// callbacks without removing the pending events.
private:
// PRIVATE TYPES
// ================
// struct EventData
// ================
struct EventData {
// This 'struct' encapsulates all of the information for a
// non-recurring event.
public:
// DATA
bsl::function<void()> d_callback;
// user-supplied callback invoked when associated event triggers
bsl::function<bsls::Types::Int64()> d_nowOffset;
// a function that returns the difference, in microseconds, between
// when the scheduled event is meant to occur and the current time
private:
// NOT IMPLEMENTED
EventData& operator=(const EventData&);
public:
// TRAITS
BSLMF_NESTED_TRAIT_DECLARATION(EventData, bslma::UsesBslmaAllocator);
// CREATORS
EventData(
const bsl::function<void()>& callback,
const bsl::function<bsls::Types::Int64()>& nowOffset,
bslma::Allocator *basicAllocator = 0)
// Create an 'EventData' from the specified 'callback' and
// 'nowOffset'. Optionally specify a 'basicAllocator' used to
// supply memory. If 'basicAllocator' is 0, the currently
// installed default allocator is used.
: d_callback(bsl::allocator_arg, basicAllocator, callback)
, d_nowOffset(bsl::allocator_arg, basicAllocator, nowOffset)
{
}
EventData(const EventData& original,
bslma::Allocator *basicAllocator = 0)
// Create an 'EventData' object having the value of the specified
// 'original' object. Optionally specify a 'basicAllocator' used
// to supply memory. If 'basicAllocator' is 0, the currently
// installed default allocator is used.
: d_callback(bsl::allocator_arg, basicAllocator, original.d_callback)
, d_nowOffset(bsl::allocator_arg, basicAllocator, original.d_nowOffset)
{
}
};
// =========================
// struct RecurringEventData
// =========================
struct RecurringEventData {
// This 'struct' encapsulates all of the information for a recurring
// event.
public:
// DATA
bsls::TimeInterval d_interval;
// the time between calls (in microseconds)
bsl::function<void()> d_callback;
// user-supplied callback invoked when associated event triggers
bsl::function<bsls::Types::Int64(int)> d_nowOffset;
// a function that returns the difference, in microseconds, between
// when the scheduled event is meant to occur and the current time
int d_eventIdx;
// the index of the recurring event (starting with 0); passed to
// 'd_nowOffset' to determine the time of the next invocation of
// 'd_callback'
private:
// NOT IMPLEMENTED
RecurringEventData& operator=(const RecurringEventData&);
public:
// TRAITS
BSLMF_NESTED_TRAIT_DECLARATION(RecurringEventData,
bslma::UsesBslmaAllocator);
// CREATORS
RecurringEventData(
const bsls::TimeInterval& interval,
const bsl::function<void()>& callback,
const bsl::function<bsls::Types::Int64(int)>& nowOffset,
bslma::Allocator *basicAllocator = 0)
// Create a 'RecurringEventData' from the specified 'interval',
// 'callback', and 'nowOffset'. Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is
// 0, the currently installed default allocator is used.
: d_interval(interval)
, d_callback(bsl::allocator_arg, basicAllocator, callback)
, d_nowOffset(bsl::allocator_arg, basicAllocator, nowOffset)
, d_eventIdx(0)
{
}
RecurringEventData(const RecurringEventData& original,
bslma::Allocator *basicAllocator = 0)
// Create a 'RecurringEventData' object having the value of the
// specified 'original' object. Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is
// 0, the currently installed default allocator is used.
: d_interval(original.d_interval)
, d_callback(bsl::allocator_arg, basicAllocator, original.d_callback)
, d_nowOffset(bsl::allocator_arg, basicAllocator, original.d_nowOffset)
, d_eventIdx(original.d_eventIdx)
{
}
};
typedef bdlcc::SkipList<bsls::Types::Int64,
RecurringEventData> RecurringEventQueue;
typedef bdlcc::SkipList<bsls::Types::Int64, EventData> EventQueue;
typedef bsl::function<bsls::TimeInterval()> CurrentTimeFunctor;
// FRIENDS
friend class EventSchedulerEventHandle;
friend class EventSchedulerRecurringEventHandle;
friend class EventSchedulerTestTimeSource;
public:
// PUBLIC TYPES
struct Event {};
struct RecurringEvent {};
// Pointers to the opaque structures 'Event' and 'RecurringEvent' are
// populated by the "Raw" API of 'EventScheduler'.
typedef EventSchedulerEventHandle EventHandle;
typedef EventSchedulerRecurringEventHandle RecurringEventHandle;
typedef bsl::function<void(const bsl::function<void()>&)>
Dispatcher;
// Defines a type alias for the dispatcher functor type.
private:
// NOT IMPLEMENTED
EventScheduler(const EventScheduler&);
EventScheduler& operator=(const EventScheduler&);
private:
// PRIVATE CLASS DATA
static const char s_defaultThreadName[16]; // Thread name to use when
// none is specified.
// PRIVATE DATA
CurrentTimeFunctor d_currentTimeFunctor; // when called, returns the
// current time the scheduler
// should use for the event
// timeline
EventQueue d_eventQueue; // events
RecurringEventQueue d_recurringQueue; // recurring events
Dispatcher d_dispatcherFunctor; // dispatch events
bslmt::ThreadUtil::Handle
d_dispatcherThread; // dispatcher thread handle
bsls::AtomicUint64 d_dispatcherThreadId; // dispatcher thread id used to
// implement function
// 'isInDispatcherThread'
bslmt::Mutex d_dispatcherMutex; // serialize starting/stopping
// dispatcher thread
mutable bslmt::Mutex d_mutex; // synchronizes access to
// condition variables
bslmt::Condition d_queueCondition; // condition variable used to
// signal when the queues need
// to be checked again (when
// they become non-empty or get
// a new front member)
bslmt::Condition d_iterationCondition; // condition variable used to
// signal when the dispatcher
// is ready to enter next
// iteration (synchronizes
// 'wait' methods)
bool d_running; // controls the looping of the
// dispatcher thread
bool d_dispatcherAwaited; // A thread is waiting for the
// dispatcher to complete an
// iteration
RecurringEventQueue::Pair
*d_currentRecurringEvent;
// Raw reference to the
// scheduled event being
// executed
EventQueue::Pair *d_currentEvent;
// Raw reference to the
// scheduled recurring event
// being executed
unsigned int d_waitCount; // count of the number of waits
// performed in the main
// dispatch loop, used in
// 'advanceTime' to determine
// when to return
bsls::SystemClockType::Enum
d_clockType; // clock type used
// PRIVATE CLASS METHODS
static bsls::Types::Int64 returnZero();
// Return 0.
static bsls::Types::Int64 returnZeroInt(int);
// Return 0. The 'int' argument is ignored.
#ifdef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY
template <class CLOCK, class DURATION>
static bsls::Types::Int64
timeUntilTrigger(const bsl::chrono::time_point<CLOCK, DURATION>& absTime);
// Return the number of microseconds between the current time and the
// specified 'absTime'. 'absTime' is an *absolute* time represented as
// an interval from some epoch, which is determined by the clock
// associated with the time point. Note that this method is used when
// the 'CLOCK' type used to schedule the event differs from that of the
// event scheduler itself. Also note that a negative value is returned
// if 'absTime' is in the past.
template <class CLOCK, class DURATION, class REP_TYPE, class PERIOD_TYPE>
static bsls::Types::Int64 timeUntilTriggerRecurring(
const bsl::chrono::time_point<CLOCK, DURATION>& absTime,
const bsl::chrono::duration<REP_TYPE, PERIOD_TYPE>& interval,
int eventIndex);
// Return the number of microseconds between the current time and the
// scheduled time of the specified 'eventIndex'th recurring event,
// which starts at the specified 'absTime' and repeats at the specified
// 'interval'. 'absTime' is an *absolute* time represented as an
// interval from some epoch, which is determined by the clock
// associated with the time point. The behavior is undefined unless
// '0 <= eventIndex'. Note that this method is used when the 'CLOCK'
// type used to schedule the event differs from that of the event
// scheduler itself.
#endif
// PRIVATE MANIPULATORS
bsls::Types::Int64 chooseNextEvent(bsls::Types::Int64 *now);
// Pick either 'd_currentEvent' or 'd_currentRecurringEvent' as the
// next event to be executed, given that the current time is the
// specified (absolute) 'now' interval, and return the (absolute)
// interval of the chosen event. If both 'd_currentEvent' and
// 'd_currentRecurringEvent' are valid, release whichever one was not
// chosen. If both 'd_currentEvent' and 'd_currentRecurringEvent' are
// scheduled before 'now', choose 'd_currentEvent'. The behavior is
// undefined if neither 'd_currentEvent' nor 'd_currentRecurringEvent'
// is valid. Note that the argument and return value of this method
// are expressed in terms of the number of microseconds elapsed since
// some epoch, which is determined by the clock indicated at
// construction (see {Supported Clock Types} in the component
// documentation). Also note that this method may update the value of
// 'now' with the current system time if necessary.
void dispatchEvents();
// While d_running is true, execute events in the event and recurring
// event queues at their scheduled times. Note that this method
// implements the dispatching thread.
void releaseCurrentEvents();
// Release 'd_currentRecurringEvent' and 'd_currentEvent', if they
// refer to valid events.
void scheduleEvent(EventHandle *event,
const bsls::TimeInterval& epochTime,
const EventData& eventData);
// Schedule the callback of the specified 'eventData' to be dispatched
// at the specified 'epochTime' truncated to microseconds. Load into
// the specified 'event' pointer a handle that can be used to cancel
// the event (by invoking 'cancelEvent'). The 'epochTime' is an
// absolute time represented as an interval from some epoch, which is
// determined by the clock indicated at construction (see {Supported
// Clock Types} in the component documentation). Note that if
// 'epochTime' is in the past, the event is dispatched immediately.
void scheduleEvent(const bsls::TimeInterval& epochTime,
const EventData& eventData);
// Schedule the callback of the specified 'eventData' to be dispatched
// at the specified 'epochTime' truncated to microseconds. The
// 'epochTime' is an absolute time represented as an interval from some
// epoch, which is determined by the clock indicated at construction
// (see {Supported Clock Types} in the component documentation). Note
// that if 'epochTime' is in the past, the event is dispatched
// immediately.
void scheduleRecurringEvent(RecurringEventHandle *event,
const RecurringEventData& eventData,
const bsls::TimeInterval& startEpochTime);
// Schedule a recurring event that invokes the callback of the
// specified 'eventData' with the first event dispatched at the
// specified 'startEpochTime' truncated to microseconds. Load into the
// specified 'event' pointer a handle that can be used to cancel the
// event (by invoking 'cancelEvent'). The 'startEpochTime' is an
// absolute time represented as an interval from some epoch, which is
// determined by the clock indicated at construction (see {Supported
// Clock Types} in the component documentation). The behavior is
// undefined unless the interval of 'eventData' is at least one
// microsecond. Note that if 'startEpochTime' is in the past, the
// first event is dispatched immediately, and additional
// '(now() - startEpochTime) / eventData.d_interval' events will be
// submitted serially.
void scheduleRecurringEventRaw(RecurringEvent **event,
const RecurringEventData& eventData,
const bsls::TimeInterval& startEpochTime);
// Schedule a recurring event that invokes the callback of the
// specified 'eventData' with the first event dispatched at the
// specified 'startEpochTime' truncated to microseconds. Load into the
// specified 'event' pointer a handle that can be used to cancel the
// event (by invoking 'cancelEvent'). The 'startEpochTime' is an
// *absolute* time represented as an interval from some epoch, which is
// determined by the clock indicated at construction (see {Supported
// Clock Types} in the component documentation). The 'event' pointer
// must be released by invoking 'releaseEventRaw' when it is no longer
// needed. The behavior is undefined unless the interval of
// 'eventData' is at least one microsecond. Note that if
// 'startEpochTime' is in the past, the first event is dispatched
// immediately, and additional
// '(now() - startEpochTime) / eventData.d_interval' events will be
// submitted serially.
public:
// TRAITS
BSLMF_NESTED_TRAIT_DECLARATION(EventScheduler, bslma::UsesBslmaAllocator);
// CREATORS
explicit EventScheduler(bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the default dispatcher functor (see
// {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system realtime clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
explicit EventScheduler(bsls::SystemClockType::Enum clockType,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the default dispatcher functor (see
// {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the specified 'clockType'
// to indicate the epoch used for all time intervals (see {Supported
// Clock Types} in the component documentation). Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is 0,
// the currently installed default allocator is used.
#ifdef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY
explicit EventScheduler(
const bsl::chrono::system_clock&,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the default dispatcher functor (see
// {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system realtime clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
explicit EventScheduler(
const bsl::chrono::steady_clock&,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the default dispatcher functor (see
// {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system monotonic clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
#endif
explicit EventScheduler(const Dispatcher& dispatcherFunctor,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the specified 'dispatcherFunctor'
// (see {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system realtime clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
EventScheduler(const Dispatcher& dispatcherFunctor,
bsls::SystemClockType::Enum clockType,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the specified 'dispatcherFunctor'
// (see {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the specified 'clockType'
// to indicate the epoch used for all time intervals (see {Supported
// Clock Types} in the component documentation). Optionally specify a
// 'basicAllocator' used to supply memory. If 'basicAllocator' is 0,
// the currently installed default allocator is used.
#ifdef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY
EventScheduler(const Dispatcher& dispatcherFunctor,
const bsl::chrono::system_clock&,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the specified 'dispatcherFunctor'
// (see {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system realtime clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
EventScheduler(const Dispatcher& dispatcherFunctor,
const bsl::chrono::steady_clock&,
bslma::Allocator *basicAllocator = 0);
// Create an event scheduler using the specified 'dispatcherFunctor'
// (see {The Dispatcher Thread and the Dispatcher Functor} in the
// component-level documentation) and using the system monotonic clock
// to indicate the epoch used for all time intervals. Optionally
// specify a 'basicAllocator' used to supply memory. If
// 'basicAllocator' is 0, the currently installed default allocator is
// used.
#endif
~EventScheduler();
// Discard all unprocessed events and destroy this object. The
// behavior is undefined unless the scheduler is stopped.
// MANIPULATORS
void cancelAllEvents();
// Cancel all recurring and one-time events scheduled in this
// EventScheduler.
void cancelAllEventsAndWait();
// Cancel all recurring and one-time events scheduled in this
// EventScheduler. Block until all events have either been cancelled
// or dispatched before this call returns. The behavior is undefined
// if this method is invoked from the dispatcher thread.
int cancelEvent(const Event *handle);
int cancelEvent(const RecurringEvent *handle);
// Cancel the event having the specified 'handle'. Return 0 on
// successful cancellation, and a non-zero value if the 'handle' is
// invalid *or* if the event has already been dispatched or canceled.
// Note that due to the implicit conversion from Handle types, these
// methods also match the following:
//..
// int cancelEvent(const EventHandle& handle);
// int cancelEvent(const RecurringEventHandle& handle);
//..
// Compared to the version taking a pointer to Handle, the managed
// reference to the event is not released until the Handle goes out of
// scope.
int cancelEvent(EventHandle *handle);
int cancelEvent(RecurringEventHandle *handle);
// Cancel the event having the specified 'handle' and release the
// handle. Return 0 on successful cancellation, and a non-zero value
// if the 'handle' is invalid *or* if the event has already been
// dispatched or canceled. Note that 'handle' is released whether this
// call is successful or not.
int cancelEventAndWait(const Event *handle);
int cancelEventAndWait(const RecurringEvent *handle);
// Cancel the event having the specified 'handle'. Block until the
// event having 'handle' (if it is valid) is either successfully
// canceled or dispatched before the call returns. Return 0 on
// successful cancellation, and a non-zero value if 'handle' is invalid
// *or* if the event has already been dispatched or canceled. The
// behavior is undefined if this method is invoked from the dispatcher
// thread. Note that if the event is being executed when this method
// is invoked, this method will block until it is completed and then
// return a nonzero value.
int cancelEventAndWait(EventHandle *handle);
int cancelEventAndWait(RecurringEventHandle *handle);
// Cancel the event having the specified 'handle' and release
// '*handle'. Block until the event having 'handle' (if it is valid)
// is either successfully canceled or dispatched before the call
// returns. Return 0 on successful cancellation, and a non-zero value
// if 'handle' is invalid *or* if the event has already been dispatched
// or canceled. The behavior is undefined if this method is invoked
// from the dispatcher thread. Note that if the event is being
// executed when this method is invoked, this method will block until
// it is completed and then return a nonzero value. Also note that it
// is guaranteed that '*handle' will be released whether this call is
// successful or not.
void releaseEventRaw(Event *handle);
void releaseEventRaw(RecurringEvent *handle);
// Release the specified 'handle'. Every handle reference added by
// 'scheduleEventRaw', 'addEventRefRaw', 'scheduleRecurringEventRaw',
// or 'addRecurringEventRefRaw' must be released using this method to
// avoid leaking resources. The behavior is undefined if the value of
// 'handle' is used for any purpose after being released.
int rescheduleEvent(const Event *handle,
const bsls::TimeInterval& newEpochTime);
// Reschedule the event referred to by the specified 'handle' at the
// specified 'newEpochTime' truncated to microseconds. Return 0 on
// successful reschedule, and a non-zero value if the 'handle' is
// invalid *or* if the event has already been dispatched. The
// 'newEpochTime' is an absolute time represented as an interval from
// some epoch, which is determined by the clock indicated at
// construction (see {Supported Clock Types} in the component
// documentation).
#ifdef BSLS_LIBRARYFEATURES_HAS_CPP11_BASELINE_LIBRARY
template <class CLOCK, class DURATION>
int rescheduleEvent(
const Event *handle,
const bsl::chrono::time_point<CLOCK, DURATION>& newEpochTime);