1 | // Copyright 2020 The Marl Authors. |
2 | // |
3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
4 | // you may not use this file except in compliance with the License. |
5 | // You may obtain a copy of the License at |
6 | // |
7 | // https://www.apache.org/licenses/LICENSE-2.0 |
8 | // |
9 | // Unless required by applicable law or agreed to in writing, software |
10 | // distributed under the License is distributed on an "AS IS" BASIS, |
11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
12 | // See the License for the specific language governing permissions and |
13 | // limitations under the License. |
14 | |
15 | // Simple "hello world" example that uses marl::Event and marl::WaitGroup. |
16 | |
17 | #include "marl/defer.h" |
18 | #include "marl/event.h" |
19 | #include "marl/scheduler.h" |
20 | #include "marl/waitgroup.h" |
21 | |
22 | #include <cstdio> |
23 | |
24 | int main() { |
25 | // Create a marl scheduler using the 4 hardware threads. |
26 | // Bind this scheduler to the main thread so we can call marl::schedule() |
27 | marl::Scheduler::Config cfg; |
28 | cfg.setWorkerThreadCount(4); |
29 | |
30 | marl::Scheduler scheduler(cfg); |
31 | scheduler.bind(); |
32 | defer(scheduler.unbind()); // Automatically unbind before returning. |
33 | |
34 | constexpr int numTasks = 10; |
35 | |
36 | // Create an event that is manually reset. |
37 | marl::Event sayHello(marl::Event::Mode::Manual); |
38 | |
39 | // Create a WaitGroup with an initial count of numTasks. |
40 | marl::WaitGroup saidHello(numTasks); |
41 | |
42 | // Schedule some tasks to run asynchronously. |
43 | for (int i = 0; i < numTasks; i++) { |
44 | // Each task will run on one of the 4 worker threads. |
45 | marl::schedule([=] { // All marl primitives are capture-by-value. |
46 | // Decrement the WaitGroup counter when the task has finished. |
47 | defer(saidHello.done()); |
48 | |
49 | printf("Task %d waiting to say hello...\n" , i); |
50 | |
51 | // Blocking in a task? |
52 | // The scheduler will find something else for this thread to do. |
53 | sayHello.wait(); |
54 | |
55 | printf("Hello from task %d!\n" , i); |
56 | }); |
57 | } |
58 | |
59 | sayHello.signal(); // Unblock all the tasks. |
60 | |
61 | saidHello.wait(); // Wait for all tasks to complete. |
62 | |
63 | printf("All tasks said hello.\n" ); |
64 | |
65 | // All tasks are guaranteed to complete before the scheduler is destructed. |
66 | } |
67 | |