MCPcopy Create free account
hub / github.com/Pagghiu/SaneCppLibraries / testThreadPool

Method testThreadPool

Tests/Libraries/Threading/ThreadPoolTest.cpp:30–83  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

28};
29
30void SC::ThreadPoolTest::testThreadPool()
31{
32 //! [threadPoolSnippet]
33 static const size_t wantedThreads = 4;
34 static const size_t numTasks = 100;
35
36 // 1. Create the threadpool with the wanted number of threads
37 SC::ThreadPool threadPool;
38 SC_TEST_EXPECT(threadPool.create(wantedThreads));
39
40 size_t values[numTasks];
41
42 // 2. Allocate the wanted number of tasks. Tasks memory should be valid until a task is finished.
43 SC::ThreadPool::Task tasks[numTasks];
44
45 for (size_t idx = 0; idx < numTasks; idx++)
46 {
47 size_t* value = values + idx;
48 *value = idx;
49
50 // 3. Setup the task function to execute on some random thread
51 tasks[idx].function = [value]()
52 {
53 if (*value % 2)
54 {
55 SC::Thread::Sleep(10);
56 }
57 *value *= 100;
58 };
59 // 4. Queue the task in thread pool
60 SC_TEST_EXPECT(threadPool.queueTask(tasks[idx]));
61 }
62
63 // 5. [Optional] Wait for a single task
64 SC_TEST_EXPECT(threadPool.waitForTask(tasks[1]));
65 SC_TEST_EXPECT(values[1] == 100);
66
67 // 6. [Optional] Wait for all remaining tasks to be finished
68 SC_TEST_EXPECT(threadPool.waitForAllTasks());
69
70 // Checking Results
71 bool allGood = true;
72 for (size_t idx = 0; idx < numTasks; idx++)
73 {
74 allGood = allGood && (values[idx] == idx * 100);
75 }
76 SC_TEST_EXPECT(allGood);
77
78 // 6. [Optional] Destroy the threadpool.
79 // Note: destructor will wait for tasks to finish, but this avoids it from accessing invalid tasks,
80 // as stack objects are reclaimed in inverse declaration order
81 SC_TEST_EXPECT(threadPool.destroy());
82 //! [threadPoolSnippet]
83}
84
85void SC::ThreadPoolTest::testThreadPoolErrors()
86{

Callers

nothing calls this directly

Calls 5

queueTaskMethod · 0.80
waitForTaskMethod · 0.80
waitForAllTasksMethod · 0.80
createMethod · 0.45
destroyMethod · 0.45

Tested by

no test coverage detected