1// Copyright 2019 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#include "marl/blockingcall.h"
16
17#include "marl/defer.h"
18
19#include "marl_test.h"
20
21#include <mutex>
22
23TEST_P(WithBoundScheduler, BlockingCallVoidReturn) {
24 auto mutex = std::make_shared<std::mutex>();
25 mutex->lock();
26
27 marl::WaitGroup wg(100);
28 for (int i = 0; i < 100; i++) {
29 marl::schedule([=] {
30 defer(wg.done());
31 marl::blocking_call([=] {
32 mutex->lock();
33 defer(mutex->unlock());
34 });
35 });
36 }
37
38 mutex->unlock();
39 wg.wait();
40}
41
42TEST_P(WithBoundScheduler, BlockingCallIntReturn) {
43 auto mutex = std::make_shared<std::mutex>();
44 mutex->lock();
45
46 marl::WaitGroup wg(100);
47 std::atomic<int> n = {0};
48 for (int i = 0; i < 100; i++) {
49 marl::schedule([=, &n] {
50 defer(wg.done());
51 n += marl::blocking_call([=] {
52 mutex->lock();
53 defer(mutex->unlock());
54 return i;
55 });
56 });
57 }
58
59 mutex->unlock();
60 wg.wait();
61
62 ASSERT_EQ(n.load(), 4950);
63}
64
65TEST_P(WithBoundScheduler, BlockingCallSchedulesTask) {
66 marl::WaitGroup wg(1);
67 marl::schedule([=] {
68 marl::blocking_call([=] { marl::schedule([=] { wg.done(); }); });
69 });
70 wg.wait();
71}
72