-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
592 lines (475 loc) · 18.8 KB
/
main.cpp
File metadata and controls
592 lines (475 loc) · 18.8 KB
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
#include "DelegateLib.h"
#include "SysData.h"
#include "SysDataNoLock.h"
#include "Timer.h"
#include <iostream>
#include <sstream>
#include <thread>
#include <algorithm>
#if USE_STD_THREADS
#include "WorkerThreadStd.h"
#elif USE_WIN32_THREADS
#include "WorkerThreadWin.h"
#endif
// main.cpp
// @see https://github.com/endurodave/AsyncMulticastDelegateCpp17
using namespace std;
using namespace DelegateLib;
WorkerThread workerThread1("WorkerThread1");
#if 0 // Not reliable
struct DumpLeaks
{
~DumpLeaks() {
#ifndef USE_XALLOCATOR
BOOL leaks = _CrtDumpMemoryLeaks();
ASSERT_TRUE(leaks == FALSE);
#endif
}
};
static DumpLeaks dumpLeaks;
#endif
/// @brief Test client to get callbacks from SysData::SystemModeChangedDelgate and
/// SysDataNoLock::SystemModeChangedDelegate
class SysDataClient
{
public:
// Constructor
SysDataClient() :
m_numberOfCallbacks(0)
{
// Register for async delegate callbacks
SysData::GetInstance().SystemModeChangedDelegate += MakeDelegate(this, &SysDataClient::CallbackFunction, workerThread1);
SysDataNoLock::GetInstance().SystemModeChangedDelegate += MakeDelegate(this, &SysDataClient::CallbackFunction, workerThread1);
}
~SysDataClient()
{
// Unregister the all registered delegates at once
SysData::GetInstance().SystemModeChangedDelegate.Clear();
// Alternatively unregister a single delegate
SysDataNoLock::GetInstance().SystemModeChangedDelegate -= MakeDelegate(this, &SysDataClient::CallbackFunction, workerThread1);
}
private:
void CallbackFunction(const SystemModeChanged& data)
{
m_numberOfCallbacks++;
cout << "CallbackFunction " << data.CurrentSystemMode << endl;
}
int m_numberOfCallbacks;
};
struct TestStruct
{
int x;
};
struct TestStructNoCopy
{
TestStructNoCopy(int _x) { x = _x; }
int x;
private:
// Prevent copying objects
TestStructNoCopy(const TestStructNoCopy&) = delete;
TestStructNoCopy& operator=(const TestStructNoCopy&) = delete;
};
void FreeFunc()
{
cout << "FreeFunc" << endl;
}
void FreeFuncInt(int value)
{
cout << "FreeFuncInt " << value << endl;
}
int FreeFuncRetInt()
{
cout << "FreeFuncRetInt " << endl;
return 567;
}
int FreeFuncIntRetInt(int value)
{
cout << "FreeFuncIntRetInt " << value << endl;
return value;
}
void FreeFuncPtrTestStruct(TestStruct* value)
{
cout << "FreeFuncTestStruct" << value->x << endl;
}
void FreeFuncPtrPtrTestStruct(TestStruct** value)
{
cout << "FreeFuncPtrPtrTestStruct " << (*value)->x << endl;
}
void FreeFuncRefTestStruct(const TestStruct& value)
{
cout << "FreeFuncRefTestStruct " << value.x << endl;
}
class TestClass
{
public:
~TestClass()
{
}
void MemberFunc(TestStruct* value)
{
cout << "MemberFunc " << value->x << endl;
}
void MemberFuncThreeArgs(const TestStruct& value, float f, int** i)
{
cout << "MemberFuncThreeArgs " << value.x << " " << f << " " << (**i) << endl;
}
void MemberFuncNoCopy(TestStructNoCopy* value)
{
cout << "MemberFuncNoCopy " << value->x << endl;
}
void MemberFuncNoCopyShared(std::shared_ptr<TestStructNoCopy> value)
{
cout << "MemberFuncNoCopyShared " << value->x << endl;
}
void MemberFuncStdString(const std::string& s, int year)
{
cout << "MemberFuncStdString " << s.c_str() << " " << year << endl;
}
int MemberFuncStdStringRetInt(std::string& s)
{
s = "Hello world";
return 2022;
}
static void StaticFunc(TestStruct* value)
{
cout << "StaticFunc " << value->x << endl;
}
int TestFunc()
{
cout << "TestFunc " << endl;
return 987;
}
void TestFuncNoRet()
{
cout << "TestFuncNoRet " << endl;
}
TestStruct TestFuncUserTypeRet()
{
TestStruct t;
t.x = 777;
return t;
}
};
// Class template specialization "tells" the delegate library that TestStructNoCopy* function
// arguments not to create a heap copy of TestStructNoCopy for traveling through the
// message queue. Instead the pointer argument is passed to the asynchronously invoked callback
// function as is.
namespace DelegateLib
{
template <>
class DelegateParam<TestStructNoCopy *>
{
public:
static TestStructNoCopy* New(TestStructNoCopy* param) { return param; }
static void Delete(TestStructNoCopy* param) {}
};
}
// An instance of TestStructNoCopy guaranteed to exist when the asynchronous callback occurs.
static TestStructNoCopy testStructNoCopy(999);
void TimerExpiredCb(void)
{
static int count = 0;
cout << "TimerExpiredCb " << count++ << endl;
}
class RemoteData
{
public:
RemoteData(int x, int y) : m_x(x), m_y(y) {}
RemoteData() = default;
int GetX() { return m_x; }
int GetY() { return m_y; }
private:
int m_x = 0;
int m_y = 0;
friend std::ostream& operator<< (std::ostream& out, const RemoteData& data)
{
out << data.m_x << std::endl;
out << data.m_y << std::endl;
return out;
}
friend std::istream& operator>> (std::istream& in, RemoteData& data)
{
in >> data.m_x;
in >> data.m_y;
return in;
}
};
class Coordinates
{
public:
int x = 0;
int y = 0;
};
class CoordinatesHandler
{
public:
static MulticastDelegateSafe<void(const std::shared_ptr<const Coordinates>)> CoordinatesChanged;
void SetData(const Coordinates& data)
{
m_data = data;
CoordinatesChanged(std::make_shared<const Coordinates>(m_data));
}
private:
Coordinates m_data;
};
MulticastDelegateSafe<void(const std::shared_ptr<const Coordinates>)> CoordinatesHandler::CoordinatesChanged;
void CoordinatesChangedCallback(const std::shared_ptr<const Coordinates> c)
{
cout << "New coordinates " << c->x << " " << c->y << endl;
}
// Do not allow shared_ptr references. Causes compile error if used with Async delegates.
void CoordinatesChangedCallbackError(std::shared_ptr<const Coordinates>& c) {}
void CoordinatesChangedCallbackError2(const std::shared_ptr<const Coordinates>& c) {}
void CoordinatesChangedCallbackError3(std::shared_ptr<const Coordinates>* c) {}
void CoordinatesChangedCallbackError4(const std::shared_ptr<const Coordinates>* c) {}
extern void DelegateUnitTests();
//------------------------------------------------------------------------------
// main
//------------------------------------------------------------------------------
int main(void)
{
TestStruct testStruct;
testStruct.x = 123;
TestStruct* pTestStruct = &testStruct;
TestClass testClass;
// Create the worker threads
workerThread1.CreateThread();
SysDataNoLock::GetInstance();
#if USE_WIN32_THREADS
// Start the worker threads
ThreadWin::StartAllThreads();
#endif
// Create a timer that expires every 250mS and calls
// TimerExpiredCb on workerThread1 upon expiration
Timer timer;
timer.Expired = MakeDelegate(&TimerExpiredCb, workerThread1);
timer.Start(std::chrono::milliseconds(250));
// Run all unit tests (uncomment to run unit tests)
#ifdef DELEGATE_UNIT_TESTS
DelegateUnitTests();
#endif
// Create a delegate bound to a free function then invoke
DelegateFree<void(int)> delegateFree = MakeDelegate(&FreeFuncInt);
delegateFree(123);
// Create a delegate bound to a member function then invoke
DelegateMember<TestClass, void (TestStruct*)> delegateMember = MakeDelegate(&testClass, &TestClass::MemberFunc);
delegateMember(&testStruct);
// Create a delegate bound to a member function. Assign and invoke from
// a base reference.
DelegateMember<TestClass, void (TestStruct*)> delegateMember2 = MakeDelegate(&testClass, &TestClass::MemberFunc);
delegateMember2(&testStruct);
// Create a multicast delegate container that accepts Delegate<void (int)> delegates.
// Any function with the signature "void Func(int)".
MulticastDelegate<void (int)> delegateA;
// Add a DelegateFree1<int> delegate to the container
delegateA += MakeDelegate(&FreeFuncInt);
// Invoke the delegate target free function FreeFuncInt()
if (delegateA)
delegateA(123);
// Remove the delegate from the container
delegateA -= MakeDelegate(&FreeFuncInt);
// Create a multicast delegate container that accepts Delegate<void (TestStruct*)> delegates
// Any function with the signature "void Func(TestStruct*)".
MulticastDelegate<void(TestStruct*)> delegateB;
// Add a DelegateMember<TestStruct*> delegate to the container
delegateB += MakeDelegate(&testClass, &TestClass::MemberFunc);
// Invoke the delegate target member function TestClass::MemberFunc()
if (delegateB)
delegateB(&testStruct);
// Remove the delegate from the container
delegateB -= MakeDelegate(&testClass, &TestClass::MemberFunc);
// Create a thread-safe multicast delegate container that accepts Delegate<void (TestStruct*)> delegates
// Any function with the signature "void Func(TestStruct*)".
MulticastDelegateSafe<void (TestStruct*)> delegateC;
// Add a DelegateMember<TestStruct*> delegate to the container that will invoke on workerThread1
delegateC += MakeDelegate(&testClass, &TestClass::MemberFunc, workerThread1);
// Asynchronously invoke the delegate target member function TestClass::MemberFunc()
if (delegateC)
delegateC(&testStruct);
// Remove the delegate from the container
delegateC -= MakeDelegate(&testClass, &TestClass::MemberFunc, workerThread1);
// Create a thread-safe multicast delegate container that accepts Delegate<void (TestStruct&, float, int**)> delegates
// Any function with the signature "void Func(const TestStruct&, float, int**)".
MulticastDelegateSafe<void (const TestStruct&, float, int**)> delegateD;
// Add a DelegateMember1<TestStruct*> delegate to the container that will invoke on workerThread1
delegateD += MakeDelegate(&testClass, &TestClass::MemberFuncThreeArgs, workerThread1);
// Asynchronously invoke the delegate target member function TestClass::MemberFuncThreeArgs()
if (delegateD)
{
int i = 555;
int* pI = &i;
delegateD(testStruct, 1.23f, &pI);
}
// Remove the delegate from the container
delegateD -= MakeDelegate(&testClass, &TestClass::MemberFuncThreeArgs, workerThread1);
// Create a thread-safe multicast delegate container that accepts Delegate<void (TestStructNoCopy*)> delegates
// Any function with the signature "void Func(TestStructNoCopy*)".
MulticastDelegateSafe<void (TestStructNoCopy*)> delegateE;
// Add a DelegateMember<TestStructNoCopy*> delegate to the container that will invoke on workerThread1
delegateE += MakeDelegate(&testClass, &TestClass::MemberFuncNoCopy, workerThread1);
// Asynchronously invoke the delegate target member function TestClass::MemberFuncNoCopy().
// TestStructNoCopy will not be copied and created on the heap because of DelegateParam<TestStructNoCopy *>.
// Developer must ensure the testStructNoCopy instance exists when the asynchronous callback occurs.
if (delegateE)
delegateE(&testStructNoCopy);
// Remove the delegate from the container
delegateE -= MakeDelegate(&testClass, &TestClass::MemberFuncNoCopy, workerThread1);
// Create a singlecast delegate container that accepts Delegate<int (int)> delegates.
// Any function with the signature "int Func(int)".
SinglecastDelegate<int (int)> delegateF;
// Add a DelegateFree1<int, int> delegate to the container
delegateF = MakeDelegate(&FreeFuncIntRetInt);
// Invoke the delegate target free function FreeFuncInt()
int retVal = 0;
if (delegateF)
retVal = delegateF(123);
// Remove the delegate from the container
delegateF.Clear();
// Create a singlecast delegate container that accepts delegates with
// the singature "void Func(TestStruct**)"
SinglecastDelegate<void(TestStruct**)> delegateG;
// Make a delegate that points to a free function
delegateG = MakeDelegate(&FreeFuncPtrPtrTestStruct);
// Invoke the delegate target function FreeFuncPtrPtrTestStruct()
delegateG(&pTestStruct);
// Remove the delegate from the container
delegateG = 0;
// Create delegate with std::string and int arguments then asychronously
// invoke on a member function
MulticastDelegateSafe<void(const std::string&, int)> delegateH;
delegateH += MakeDelegate(&testClass, &TestClass::MemberFuncStdString, workerThread1);
delegateH("Hello world", 2022);
delegateH.Clear();
// Create a asynchronous blocking delegate and invoke. This thread will block until the
// msg and year stack values are set by MemberFuncStdStringRetInt on workerThread1.
auto delegateI = MakeDelegate(&testClass, &TestClass::MemberFuncStdStringRetInt, workerThread1, WAIT_INFINITE);
std::string msg;
int year = delegateI(msg);
if (delegateI.IsSuccess())
cout << msg.c_str() << " " << year << endl;
#ifdef USE_CXX17
// Alternate means to invoke a function asynchronousy using AsyncInvoke. This thread will block until the
// msg and year stack values are set by MemberFuncStdStringRetInt on workerThread1.
std::string msg2;
auto asyncInvokeRetVal = MakeDelegate(&testClass, &TestClass::MemberFuncStdStringRetInt, workerThread1, WAIT_INFINITE).AsyncInvoke(msg2);
if (asyncInvokeRetVal.has_value())
cout << msg.c_str() << " " << asyncInvokeRetVal.value() << endl;
// Invoke function asynchronously with user defined return type
auto testStructRet = MakeDelegate(&testClass, &TestClass::TestFuncUserTypeRet, workerThread1, WAIT_INFINITE).AsyncInvoke();
// Invoke functions asynchronously with no return value
auto noRetValRet = MakeDelegate(&testClass, &TestClass::TestFuncNoRet, workerThread1, std::chrono::milliseconds(10)).AsyncInvoke();
auto noRetValRet2 = MakeDelegate(&FreeFuncInt, workerThread1, std::chrono::milliseconds(10)).AsyncInvoke(123);
if (noRetValRet.has_value() && noRetValRet2.has_value())
cout << "Asynchronous calls with no return value succeeded!" << endl;
#endif
// Create a shared_ptr, create a delegate, then synchronously invoke delegate function
std::shared_ptr<TestClass> spObject = std::make_shared<TestClass>();
auto delegateMemberSp = MakeDelegate(spObject, &TestClass::MemberFuncStdString);
delegateMemberSp("Hello world using shared_ptr", 2022);
// Example of a bug where the testClassHeap is deleted before the asychronous delegate
// is invoked on the workerThread1. In other words, by the time workerThread1 calls
// the bound delegate function the testClassHeap instance is deleted and no longer valid.
TestClass* testClassHeap = new TestClass();
auto delegateMemberAsync = MakeDelegate(testClassHeap, &TestClass::MemberFuncStdString, workerThread1);
delegateMemberAsync("Function async invoked on deleted object. Bug!", 2022);
delegateMemberAsync.Clear();
delete testClassHeap;
// Example of the smart pointer function version of the delegate. The testClassSp instance
// is only deleted after workerThread1 invokes the callback function thus solving the bug.
std::shared_ptr<TestClass> testClassSp = std::make_shared<TestClass>();
auto delegateMemberSpAsync = MakeDelegate(testClassSp, &TestClass::MemberFuncStdString, workerThread1);
delegateMemberSpAsync("Function async invoked using smart pointer. Bug solved!", 2022);
delegateMemberSpAsync.Clear();
testClassSp.reset();
{
// Example of a shared_ptr argument that does not copy the function
// argument data.
auto delegateJ = MakeDelegate(&testClass, &TestClass::MemberFuncNoCopyShared, workerThread1);
std::shared_ptr<TestStructNoCopy> testStructNoCopy = std::make_shared<TestStructNoCopy>(987);
delegateJ(testStructNoCopy);
}
// Example of using std::shared_ptr function arguments with asynchrononous delegate. Using a
// shared_ptr<T> argument ensures that the argument T is not copied for each registered client.
// Could be helpful if T is very large and two or more clients register to receive asynchronous
// callbacks.
CoordinatesHandler coordinatesHandler;
CoordinatesHandler::CoordinatesChanged += MakeDelegate(&CoordinatesChangedCallback, workerThread1);
Coordinates coordinates;
coordinates.x = 11;
coordinates.y = 99;
coordinatesHandler.SetData(coordinates);
#if 0
// Causes compiler error. shared_ptr references not allowed; undefined behavior
// in multithreaded system.
auto errorDel = MakeDelegate(&CoordinatesChangedCallbackError, workerThread1);
auto errorDel2 = MakeDelegate(&CoordinatesChangedCallbackError2, workerThread1);
auto errorDel3 = MakeDelegate(&CoordinatesChangedCallbackError3, workerThread1);
auto errorDel4 = MakeDelegate(&CoordinatesChangedCallbackError4, workerThread1);
#endif
// Begin lambda examples. Lambda captures not allowed if delegates used to invoke.
auto LambdaFunc1 = +[](int i) -> int
{
cout << "Called LambdaFunc1 " << i << std::endl;
return ++i;
};
auto LambdaFunc2 = +[](const TestStruct& s, bool b)
{
cout << "Called LambdaFunc2 " << s.x << " " << b << std::endl;
};
// Invoke lambda via function pointer without delegates
int lambdaRetVal1 = LambdaFunc1(876);
// Asynchronously invoke lambda on workerThread1 and wait for the return value
auto lambdaDelegate1 = MakeDelegate(LambdaFunc1, workerThread1, WAIT_INFINITE);
int lambdaRetVal2 = lambdaDelegate1(123);
TestStruct lambdaArg;
lambdaArg.x = 4321;
// Asynchronously invoke lambda on workerThread1 without waiting
auto lambdaDelegate2 = MakeDelegate(LambdaFunc2, workerThread1);
lambdaDelegate2(lambdaArg, true);
// Asynchronously invoke lambda on workerThread1 using AsyncInvoke
auto lambdaRet = MakeDelegate(LambdaFunc1, workerThread1, std::chrono::milliseconds(100)).AsyncInvoke(543);
if (lambdaRet.has_value())
cout << "LambdaFunc1 success! " << lambdaRet.value() << endl;
std::vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// Synchronous lambda example
const auto valResult = std::count_if(v.begin(), v.end(),
[](int v) { return v > 2 && v <= 6; });
cout << "Synchronous lambda result: " << valResult << endl;
// Asychronous lambda example (pass delegate to algorithm)
auto CountLambda = +[](int v) -> int
{
return v > 2 && v <= 6;
};
auto countLambdaDelegate = MakeDelegate(CountLambda, workerThread1, WAIT_INFINITE);
// Alternate syntax
//auto countLambdaDelegate = MakeDelegate(
// +[](int v) { return v > 2 && v <= 6; },
// workerThread1,
// WAIT_INFINITE);
const auto valAsyncResult = std::count_if(v.begin(), v.end(),
countLambdaDelegate);
cout << "Asynchronous lambda result: " << valAsyncResult << endl;
// End lambda examples
// Create a SysDataClient instance on the stack
SysDataClient sysDataClient;
// Set new SystemMode values. Each call will invoke callbacks to all
// registered client subscribers.
SysData::GetInstance().SetSystemMode(SystemMode::STARTING);
SysData::GetInstance().SetSystemMode(SystemMode::NORMAL);
// Set new SystemMode values for SysDataNoLock.
SysDataNoLock::GetInstance().SetSystemMode(SystemMode::SERVICE);
SysDataNoLock::GetInstance().SetSystemMode(SystemMode::SYS_INOP);
// Set new SystemMode values for SysDataNoLock using async API
SysDataNoLock::GetInstance().SetSystemModeAsyncAPI(SystemMode::SERVICE);
SysDataNoLock::GetInstance().SetSystemModeAsyncAPI(SystemMode::SYS_INOP);
// Set new SystemMode values for SysDataNoLock using async wait API
SystemMode::Type previousMode;
previousMode = SysDataNoLock::GetInstance().SetSystemModeAsyncWaitAPI(SystemMode::STARTING);
previousMode = SysDataNoLock::GetInstance().SetSystemModeAsyncWaitAPI(SystemMode::NORMAL);
timer.Stop();
timer.Expired.Clear();
std::this_thread::sleep_for(std::chrono::seconds(1));
workerThread1.ExitThread();
std::this_thread::sleep_for(std::chrono::seconds(1));
return 0;
}