| 100 | // ---------------------------------------------------------------------------------------- |
| 101 | |
| 102 | void example_using_lambda_functions() |
| 103 | { |
| 104 | cout << "\nExample using parallel for loops\n" << endl; |
| 105 | |
| 106 | std::vector<int> vect; |
| 107 | |
| 108 | vect.assign(10, -1); |
| 109 | parallel_for(0, vect.size(), [&](long i){ |
| 110 | // The i variable is the loop counter as in a normal for loop. So we simply need |
| 111 | // to place the body of the for loop right here and we get the same behavior. The |
| 112 | // range for the for loop is determined by the 1nd and 2rd arguments to |
| 113 | // parallel_for(). This way of calling parallel_for() will use a number of threads |
| 114 | // that is appropriate for your hardware. See the parallel_for() documentation for |
| 115 | // other options. |
| 116 | vect[i] = i; |
| 117 | dlib::sleep(1000); |
| 118 | }); |
| 119 | print(vect); |
| 120 | |
| 121 | |
| 122 | // Assign only part of the elements in vect. |
| 123 | vect.assign(10, -1); |
| 124 | parallel_for(1, 5, [&](long i){ |
| 125 | vect[i] = i; |
| 126 | dlib::sleep(1000); |
| 127 | }); |
| 128 | print(vect); |
| 129 | |
| 130 | |
| 131 | // Note that things become a little more complex if the loop bodies are not totally |
| 132 | // independent. In the first two cases each iteration of the loop touched different |
| 133 | // memory locations, so we didn't need to use any kind of thread synchronization. |
| 134 | // However, in the summing loop we need to add some synchronization to protect the sum |
| 135 | // variable. This is easily accomplished by creating a mutex and locking it before |
| 136 | // adding to sum. More generally, you must ensure that the bodies of your parallel for |
| 137 | // loops are thread safe using whatever means is appropriate for your code. Since a |
| 138 | // parallel for loop is implemented using threads, all the usual techniques for |
| 139 | // ensuring thread safety can be used. |
| 140 | int sum = 0; |
| 141 | dlib::mutex m; |
| 142 | vect.assign(10, 2); |
| 143 | parallel_for(0, vect.size(), [&](long i){ |
| 144 | // The sleep statements still execute in parallel. |
| 145 | dlib::sleep(1000); |
| 146 | |
| 147 | // Lock the m mutex. The auto_mutex will automatically unlock at the closing }. |
| 148 | // This will ensure only one thread can execute the sum += vect[i] statement at |
| 149 | // a time. |
| 150 | auto_mutex lock(m); |
| 151 | sum += vect[i]; |
| 152 | }); |
| 153 | |
| 154 | cout << "sum: "<< sum << endl; |
| 155 | } |
| 156 | |
| 157 | // ---------------------------------------------------------------------------------------- |
| 158 | |