1 /*
2     Copyright (c) 2005-2020 Intel Corporation
3 
4     Licensed under the Apache License, Version 2.0 (the "License");
5     you may not use this file except in compliance with the License.
6     You may obtain a copy of the License at
7 
8         http://www.apache.org/licenses/LICENSE-2.0
9 
10     Unless required by applicable law or agreed to in writing, software
11     distributed under the License is distributed on an "AS IS" BASIS,
12     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13     See the License for the specific language governing permissions and
14     limitations under the License.
15 */
16 
17 #define HARNESS_DEFINE_PRIVATE_PUBLIC 1
18 #include "harness_inject_scheduler.h"
19 #include "harness.h"
20 
21 #include "tbb/global_control.h"
22 #include "tbb/task_scheduler_init.h"
23 #include "tbb/parallel_for.h"
24 #include "tbb/blocked_range.h"
25 
allWorkersSleep()26 bool allWorkersSleep() {
27     using namespace tbb::internal;
28     using namespace tbb::internal::rml;
29 
30     unsigned sleeping_threads = 0;
31     unsigned threads = ((private_server*)market::theMarket->my_server)->my_n_thread;
32 
33     for (private_worker *l = ((private_server*)market::theMarket->my_server)->my_asleep_list_root;
34          l; l = l->my_next)
35         sleeping_threads++;
36 
37     return threads == sleeping_threads;
38 }
39 
40 class ThreadsTask {
41 public:
operator ()(const tbb::blocked_range<int> &) const42     void operator() (const tbb::blocked_range<int> &) const { }
ThreadsTask()43     ThreadsTask() {}
44 };
45 
RunAndCheckSleeping()46 static void RunAndCheckSleeping()
47 {
48     Harness::Sleep(100);
49     ASSERT(allWorkersSleep(), NULL);
50     tbb::parallel_for(tbb::blocked_range<int>(0, 100*1000, 1),
51                       ThreadsTask(), tbb::simple_partitioner());
52     Harness::Sleep(100);
53     ASSERT(allWorkersSleep(), NULL);
54 }
55 
56 // test that all workers are sleeping, not spinning
TestWorkersSleep()57 void TestWorkersSleep() {
58     tbb::task_scheduler_init tsi(8);
59     const size_t max_parallelism =
60         tbb::global_control::active_value(tbb::global_control::max_allowed_parallelism);
61     if (max_parallelism > 2) {
62         tbb::global_control c(tbb::global_control::max_allowed_parallelism, max_parallelism-1);
63     }
64     RunAndCheckSleeping();
65     tbb::global_control c(tbb::global_control::max_allowed_parallelism, max_parallelism+1);
66     RunAndCheckSleeping();
67 }
68 
TestMain()69 int TestMain () {
70     {
71         tbb::task_scheduler_init tsi;
72         if (!tbb::internal::governor::UsePrivateRML)
73             return Harness::Skipped;
74     }
75     TestWorkersSleep();
76 
77     return Harness::Done;
78 }
79