| 147 | } |
| 148 | |
| 149 | inline void TaskThread::wait() |
| 150 | { |
| 151 | if (! flag.test_and_set (std::memory_order_acquire)) |
| 152 | return; |
| 153 | |
| 154 | uint32_t numTries = 0; |
| 155 | |
| 156 | auto yieldOrSleep = [&numTries] |
| 157 | { |
| 158 | static constexpr uint32_t numTriesBeforeSleeping = 1000; |
| 159 | static constexpr uint32_t sleepDuration = 5; |
| 160 | |
| 161 | if (numTries == numTriesBeforeSleeping) |
| 162 | { |
| 163 | std::this_thread::sleep_for (std::chrono::milliseconds (sleepDuration)); |
| 164 | } |
| 165 | else |
| 166 | { |
| 167 | std::this_thread::yield(); |
| 168 | ++numTries; |
| 169 | } |
| 170 | }; |
| 171 | |
| 172 | if (interval != 0) |
| 173 | { |
| 174 | auto timeout = std::chrono::high_resolution_clock::now() |
| 175 | + std::chrono::milliseconds (interval); |
| 176 | |
| 177 | for (;;) |
| 178 | { |
| 179 | yieldOrSleep(); |
| 180 | |
| 181 | if (! flag.test_and_set (std::memory_order_acquire)) |
| 182 | return; |
| 183 | |
| 184 | if (std::chrono::high_resolution_clock::now() >= timeout) |
| 185 | return; |
| 186 | } |
| 187 | } |
| 188 | else |
| 189 | { |
| 190 | for (;;) |
| 191 | { |
| 192 | yieldOrSleep(); |
| 193 | |
| 194 | if (! flag.test_and_set (std::memory_order_acquire)) |
| 195 | return; |
| 196 | } |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | |
| 201 | } // namespace choc::threading |