| 1 | #cxx . . $ `<file>/melder/MelderThread.h`/ifndef _MelderThread_h_ |
| 2 | #define _MelderThread_h_cxx . . $ `melder/MelderThread.h:2:9`! |
| 3 | /* MelderThread.h |
| 4 | * |
| 5 | * Copyright (C) 2014-2018,2020,2025,2026 Paul Boersma |
| 6 | * |
| 7 | * This code is free software; you can redistribute it and/or modify |
| 8 | * it under the terms of the GNU General Public License as published by |
| 9 | * the Free Software Foundation; either version 3 of the License, or (at |
| 10 | * your option) any later version. |
| 11 | * |
| 12 | * This code is distributed in the hope that it will be useful, but |
| 13 | * WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 15 | * See the GNU General Public License for more details. |
| 16 | * |
| 17 | * You should have received a copy of the GNU General Public License |
| 18 | * along with this work. If not, see <http://www.gnu.org/licenses/>. |
| 19 | */ |
| 20 | |
| 21 | |
| 22 | integercxx . . $ integer# MelderThread_getNumberOfProcessorscxx . . $ MelderThread_getNumberOfProcessors(da6335ded91d79c2). (); |
| 23 | |
| 24 | integercxx . . $ integer# MelderThread_computeNumberOfThreadscxx . . $ MelderThread_computeNumberOfThreads(d0a0e4c270da0eca). ( |
| 25 | integercxx . . $ integer# numberOfElements, |
| 26 | integercxx . . $ integer# thresholdNumberOfElementsPerThread |
| 27 | ); |
| 28 | |
| 29 | /* |
| 30 | The following is a replacement for std::this_thread::get_id(), |
| 31 | which is not guaranteeed to return a unique ID. |
| 32 | |
| 33 | A case where this matters is if a throwing thread has finished, |
| 34 | and then a new thread is created with the same idea and quickly throws as well. |
| 35 | Admittedly, this is rare, but it is not impossible and it is easy to prevent it. |
| 36 | */ |
| 37 | integercxx . . $ integer# Melder_thisThread_getUniqueIDcxx . . $ Melder_thisThread_getUniqueID(da6335ded91d79c2). (); |
| 38 | |
| 39 | void MelderThread_runcxx . . $ MelderThread_run(8021a2f84a35715d). ( |
| 40 | stdcxx . . $ std/::atomiccxx . . $ std/atomic# <bool> *p_errorFlag, |
| 41 | integercxx . . $ integer# numberOfElements, |
| 42 | integercxx . . $ integer# thresholdNumberOfElementsPerThread, |
| 43 | stdcxx . . $ std/::functioncxx . . $ std/function# <void (integercxx . . $ integer# threadNumber, integercxx . . $ integer# firstElement, integercxx . . $ integer# lastElement)> const& threadFunction |
| 44 | ); |
| 45 | |
| 46 | /* |
| 47 | Here is how these functions help you create simple parallel procedures. |
| 48 | Our example is pitch analysis in Praat (see fon/Sound_to_Pitch.cpp for details). |
| 49 | |
| 50 | You start with defining the function: |
| 51 | |
| 52 | autoPitch Sound_to_Pitch (Sound me, integer maxnCandidates, ...) |
| 53 | { |
| 54 | |
| 55 | The function can throw: |
| 56 | try { |
| 57 | |
| 58 | Then you create the result of the function: |
| 59 | |
| 60 | autoPitch thee = Pitch_create (...); |
| 61 | |
| 62 | Then you create the intermediate objects that are read-only for all threads |
| 63 | (so that you have to create them only once): |
| 64 | |
| 65 | autoVEC window = ...; // the window shape |
| 66 | autoVEC windowR = ...; // the autocorrelation of the window shape |
| 67 | |
| 68 | You can open a progress bar if you want: |
| 69 | |
| 70 | autoMelderProgress progress (U"Sound to Pitch..."); |
| 71 | |
| 72 | Then you define the "thread function", which is a lambda that is called for every thread. |
| 73 | The thread function is not allowed to throw exceptions, because exceptions cannot pass |
| 74 | directly from a newly spawned thread into the master thread. Therefore, |
| 75 | any exception generated with the thread function has to translate each MelderError |
| 76 | into an error flag: |
| 77 | |
| 78 | std::atomic <bool> errorFlag = false; |
| 79 | |
| 80 | You then define the thread function as a lambda. |
| 81 | We hand all local variables over to the thread function by reference, |
| 82 | because many variables (namely those that have to change, such as `errorFlag`, |
| 83 | and those whose copy constructor has been deleted, |
| 84 | such as our autoPitch `thee` and our autoVECs `window` and `windowR`, |
| 85 | cannot be copied into the lambda. |
| 86 | |
| 87 | auto Sound_to_Pitch_threadFunction = [&] (integer threadNumber, integer firstFrame, integer lastFrame) { |
| 88 | |
| 89 | We could also have said [=, & errorFlag, & thee, & window, & windowR], |
| 90 | whereby most variables would have been handed over to the lambda by value, |
| 91 | but simply handing over all variables by reference is more straightforward and not really slower. |
| 92 | |
| 93 | The thread function can throw, so you need a `try`-`catch` pair: |
| 94 | try { |
| 95 | |
| 96 | In case the thread function can call NUMrandom functions, |
| 97 | they should be thread-aware (for Sound_to_Pitch, this is not the case though): |
| 98 | |
| 99 | NUMrandom_setChannel (threadNumber); |
| 100 | |
| 101 | Inside the thread function you first create the objects that are different for each thread, such as buffers: |
| 102 | |
| 103 | autoMAT frame = zero_MAT (my ny, ...); |
| 104 | autoNUMFourierTable fftTable = NUMFourierTable_create (...); |
| 105 | autoVEC ac = zero_VEC (...); |
| 106 | autoVEC rbuffer = zero_VEC (...); |
| 107 | double *r = & rbuffer [...]; |
| 108 | autoINTVEC imax = zero_INTVEC (maxnCandidates); |
| 109 | autoVEC localMean = zero_VEC (my ny); |
| 110 | |
| 111 | You can now cycle over the frames that belong to the thread: |
| 112 | |
| 113 | for (integer iframe = firstFrame; iframe <= lastFrame; iframe ++) { |
| 114 | |
| 115 | Each frame provides an opportunity to bail out from the thread function (and therefore to abort the thread): |
| 116 | |
| 117 | if (errorFlag) |
| 118 | return; // abort this thread |
| 119 | |
| 120 | If not aborted, you can now do the pitch analysis for the present frame: |
| 121 | |
| 122 | Pitch_Frame pitchFrame = & thy frames [iframe]; |
| 123 | Sound_into_PitchFrame (me, pitchFrame, maxnCandidates, |
| 124 | window.get(), windowR.get(), |
| 125 | frame.get(), fftTable.get(), ac.get(), |
| 126 | r, imax.get(), localMean.get() |
| 127 | ); |
| 128 | |
| 129 | You can update the progress bar if you are in the master thread, which has threadNumber 0. |
| 130 | You can do that anywhere in the frame loop; here we do it at the end of it: |
| 131 | |
| 132 | if (threadNumber == 0) { |
| 133 | const double estimatedFractionAnalysed = (iframe - firstFrame + 0.5) / (lastFrame - firstFrame + 1.0); |
| 134 | Melder_progress (0.1 + 0.8 * estimatedFractionAnalysed, |
| 135 | U"Sound to Pitch: analysed approximately ", Melder_iround (numberOfFrames * estimatedFractionAnalysed), |
| 136 | U" out of ", numberOfFrames, U" frames" |
| 137 | ); |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | The `catch` differs from the normal "catch (MelderError) { Melder_throw (...); }", |
| 142 | in that it has to convert the MelderError into an error flag: |
| 143 | |
| 144 | } catch (MelderError) { |
| 145 | errorFlag = true; |
| 146 | return; |
| 147 | } |
| 148 | |
| 149 | Finally, you close the lambda and call it: |
| 150 | |
| 151 | }; |
| 152 | MelderThread_run (& errorFlag, numberOfFrames, 5, false, Sound_to_Pitch_threadFunction); |
| 153 | |
| 154 | You also close the progress bar and return the result: |
| 155 | |
| 156 | Melder_progress (0.95, U"Sound to Pitch: path finder"); |
| 157 | return thee; |
| 158 | |
| 159 | You end with the `catch` of Sound_to_Pitch itself: |
| 160 | |
| 161 | } catch (MelderError) { |
| 162 | Melder_throw (me, U": pitch analysis not performed."); |
| 163 | } |
| 164 | } |
| 165 | */ |
| 166 | |
| 167 | /* |
| 168 | The above procedure can be simplified a bit by using the following four macros. |
| 169 | We surround the code by an extra pair of braces in order to allow multiple use within a function. |
| 170 | There will also be an extra pair of braces in your written code, so as to suggest scope correctly. |
| 171 | */ |
| 172 | |
| 173 | #define MelderThread_PARALLELcxx . . $ `melder/MelderThread.h:173:9`!(numberOfElements, thresholdNumberOfElementsPerThread) \ |
| 174 | {/* start of scope of `_errorFlag_` and `_threadFunction_` */ \ |
| 175 | const integer _numberOfElements_ = numberOfElements; \ |
| 176 | const integer _thresholdNumberOfElementsPerThread_ = thresholdNumberOfElementsPerThread; \ |
| 177 | std::atomic <bool> _errorFlag_ = false; \ |
| 178 | auto _threadFunction_ = [&] (integer _threadNumber_, integer _firstElement_, integer _lastElement_) { \ |
| 179 | try { \ |
| 180 | NUMrandom_setChannel (_threadNumber_); \ |
| 181 | Melder_thisThread_setRange (_firstElement_, _lastElement_); |
| 182 | |
| 183 | #define MelderThread_FORcxx . . $ `melder/MelderThread.h:183:9`!(ielement) \ |
| 184 | for (integer ielement = _firstElement_; ielement <= _lastElement_; ielement ++) { \ |
| 185 | if (_errorFlag_) \ |
| 186 | return; \ |
| 187 | Melder_thisThread_setCurrentElement (ielement); |
| 188 | |
| 189 | #define MelderThread_ENDPARALLELcxx . . $ `melder/MelderThread.h:189:9`! \ |
| 190 | } \ |
| 191 | } catch (MelderError) { \ |
| 192 | _errorFlag_ = true; \ |
| 193 | return; \ |
| 194 | } \ |
| 195 | }; \ |
| 196 | MelderThread_run (& _errorFlag_, _numberOfElements_, _thresholdNumberOfElementsPerThread_, _threadFunction_); \ |
| 197 | }/* end of scope of `_errorFlag_` and `_threadFunction_` */ |
| 198 | |
| 199 | #define MelderThread_IS_MASTERcxx . . $ `melder/MelderThread.h:199:9`! \ |
| 200 | (NUMrandom_getChannel () == 0) |
| 201 | |
| 202 | #define MelderThread_ESTIMATED_PROGRESScxx . . $ `melder/MelderThread.h:202:9`! \ |
| 203 | Melder_thisThread_estimateProgress () |
| 204 | |
| 205 | /* |
| 206 | The whole Sound_to_Pitch then becomes: |
| 207 | |
| 208 | autoPitch Sound_to_Pitch (Sound me, integer maxnCandidates, ...) |
| 209 | { |
| 210 | try { |
| 211 | autoPitch thee = Pitch_create (...); |
| 212 | autoVEC window = ...; // the window shape |
| 213 | autoVEC windowR = ...; // the autocorrelation of the window shape |
| 214 | |
| 215 | autoMelderProgress progress (U"Sound to Pitch..."); |
| 216 | |
| 217 | MelderThread_PARALLEL (numberOfFrames, 5, false) { |
| 218 | autoMAT frame = zero_MAT (my ny, ...); |
| 219 | autoNUMFourierTable fftTable = NUMFourierTable_create (...); |
| 220 | autoVEC ac = zero_VEC (...); |
| 221 | autoVEC rbuffer = zero_VEC (...); |
| 222 | double *r = & rbuffer [...]; |
| 223 | autoINTVEC imax = zero_INTVEC (maxnCandidates); |
| 224 | autoVEC localMean = zero_VEC (my ny); |
| 225 | |
| 226 | MelderThread_FOR (iframe) { |
| 227 | Pitch_Frame pitchFrame = & thy frames [iframe]; |
| 228 | Sound_into_PitchFrame (me, pitchFrame, maxnCandidates, |
| 229 | window.get(), windowR.get(), |
| 230 | frame.get(), fftTable.get(), ac.get(), |
| 231 | r, imax.get(), localMean.get() |
| 232 | ); |
| 233 | |
| 234 | if (MelderThread_IS_MASTER) { // then we can interact with the GUI |
| 235 | const double estimatedProgress = MelderThread_ESTIMATED_PROGRESS; |
| 236 | Melder_progress (0.1 + 0.8 * estimatedProgress, |
| 237 | U"Sound to Pitch: analysed approximately ", Melder_iround (numberOfFrames * estimatedProgress), |
| 238 | U" out of ", numberOfFrames, U" frames" |
| 239 | ); |
| 240 | } |
| 241 | } |
| 242 | } MelderThread_ENDPARALLEL |
| 243 | |
| 244 | Melder_progress (0.95, U"Sound to Pitch: path finder"); |
| 245 | return thee; |
| 246 | } catch (MelderError) { |
| 247 | Melder_throw (me, U": pitch analysis not performed."); |
| 248 | } |
| 249 | } |
| 250 | */ |
| 251 | |
| 252 | /* |
| 253 | How to parallelize an existing analysis function |
| 254 | ================================================ |
| 255 | |
| 256 | Suppose you have something like |
| 257 | |
| 258 | autoPitch Sound_to_Pitch (Sound me) { |
| 259 | try { |
| 260 | autoPitch thee = ...; |
| 261 | autoVEC window = ...; // the window shape |
| 262 | autoMAT frame = zero_MAT (my ny, ...); |
| 263 | autoNUMFourierTable fftTable = NUMFourierTable_create (...); |
| 264 | autoVEC ac = zero_VEC (...); |
| 265 | autoVEC rbuffer = zero_VEC (...); |
| 266 | double *r = & rbuffer [...]; |
| 267 | autoVEC windowR = ...; // the autocorrelation of the window shape |
| 268 | autoINTVEC imax = zero_INTVEC (maxnCandidates); |
| 269 | autoVEC localMean = zero_VEC (my ny); |
| 270 | autoMelderProgress progress (U"Sound to Pitch..."); |
| 271 | for (integer iframe = 1; iframe <= thy nx; iframe ++) { |
| 272 | Pitch_Frame pitchFrame = & thy frames [iframe]; |
| 273 | const double fractionAnalysed = (double) iframe / thy nx; |
| 274 | Melder_progress (0.1 + 0.8 * fractionAnalysed, |
| 275 | U"Sound to Pitch: analysed ", iframe, |
| 276 | U" out of ", thy nx, U" frames" |
| 277 | ); |
| 278 | Sound_into_PitchFrame (me, pitchFrame, maxnCandidates, |
| 279 | window.get(), windowR.get(), |
| 280 | frame.get(), fftTable.get(), ac.get(), |
| 281 | r, imax.get(), localMean.get() |
| 282 | ); |
| 283 | } |
| 284 | Melder_progress (0.95, U"Sound to Pitch: path finder"); |
| 285 | return thee; |
| 286 | } catch (MelderError) { |
| 287 | Melder_throw (me, U": pitch analysis not performed."); |
| 288 | } |
| 289 | } |
| 290 | |
| 291 | The first step is to divide all those initializations into two sets: |
| 292 | 1. the ones that all threads can use at the same time; |
| 293 | these are: |
| 294 | 1a. the target Pitch object, because each thread will write a separate part of it: |
| 295 | autoPitch thee = ...; |
| 296 | 1b. the "constant" things that are computed only once, before the loop over the frames: |
| 297 | autoVEC window = ...; // the window shape |
| 298 | autoVEC windowR = ...; // the autocorrelation of the window shape |
| 299 | 1c. the initialization of the progress bar: |
| 300 | autoMelderProgress progress (U"Sound to Pitch..."); |
| 301 | 2. the ones of which each thread need its own copy, like buffers: |
| 302 | autoMAT frame = zero_MAT (my ny, ...); |
| 303 | autoNUMFourierTable fftTable = NUMFourierTable_create (...); |
| 304 | autoVEC ac = zero_VEC (...); |
| 305 | autoVEC rbuffer = zero_VEC (...); |
| 306 | double *r = & rbuffer [...]; |
| 307 | autoINTVEC imax = zero_INTVEC (maxnCandidates); |
| 308 | autoVEC localMean = zero_VEC (my ny); |
| 309 | |
| 310 | This reordering is the preparation. You then make the following simple changes: |
| 311 | 3. between 1abc and 2 above you insert: |
| 312 | MelderThread_PARALLEL (thy nx, 5, false) { |
| 313 | 4. instead of |
| 314 | for (integer iframe = 1; iframe <= thy nx; iframe ++) { |
| 315 | you write |
| 316 | MelderThread_FOR (iframe) { |
| 317 | 5. instead of the frame-loop-closing "}" you write |
| 318 | } |
| 319 | } MelderThread_ENDPARALLEL |
| 320 | 6. you update the progress bar only in the master thread, by inserting |
| 321 | if (MelderThread_IS_MASTER) { |
| 322 | and |
| 323 | } |
| 324 | 7. instead of computing the progress as |
| 325 | const double fractionAnalysed = (double) iframe / thy nx; |
| 326 | you write |
| 327 | const double fractionAnalysed = MelderThread_ESTIMATED_PROGRESS; |
| 328 | and you may reword the variable name and the text to acknowledge that this progress |
| 329 | is just an estimate; |
| 330 | 8. you tune the "thresholdNumberOfElementsPerThread" to what turns out to be fastest |
| 331 | for low numbers of threads; see `test/manually/Sound_to_Pitch.praat` for an example. |
| 332 | */ |
| 333 | |
| 334 | void MelderThread_debugMultithreadingcxx . . $ MelderThread_debugMultithreading(dd2b2d69c71f3693). (bool useMultithreading, integercxx . . $ integer# numberOfConcurrentThreadsToUse, |
| 335 | integercxx . . $ integer# minimumNumberOfElementsPerThread, bool extraAnalysisInfo); |
| 336 | |
| 337 | bool MelderThread_getUseMultithreadingcxx . . $ MelderThread_getUseMultithreading(c9857a73d68e59ba). (); |
| 338 | |
| 339 | integercxx . . $ integer# MelderThread_getMaximumNumberOfConcurrentThreadscxx . . $ MelderThread_getMaximumNumberOfConcurrentThreads(da6335ded91d79c2). (); |
| 340 | |
| 341 | integercxx . . $ integer# MelderThread_getMinimumNumberOfElementsPerThreadcxx . . $ MelderThread_getMinimumNumberOfElementsPerThread(da6335ded91d79c2). (); |
| 342 | |
| 343 | bool MelderThread_getTraceThreadscxx . . $ MelderThread_getTraceThreads(c9857a73d68e59ba). (); |
| 344 | |
| 345 | /* |
| 346 | The following two macros can be used in tracing. |
| 347 | |
| 348 | Example: |
| 349 | if (MelderThread_TRACING) |
| 350 | Melder_casual (MelderThread_CHANNEL, U" ", iframe, U" ", result); |
| 351 | */ |
| 352 | |
| 353 | #define MelderThread_TRACINGcxx . . $ `melder/MelderThread.h:353:9`! \ |
| 354 | MelderThread_getTraceThreads () |
| 355 | |
| 356 | #define MelderThread_CHANNELcxx . . $ `melder/MelderThread.h:356:9`! \ |
| 357 | NUMrandom_getChannel () |
| 358 | |
| 359 | /* |
| 360 | The following three functions are mainly on behalf of progress bars. |
| 361 | */ |
| 362 | |
| 363 | void Melder_thisThread_setRangecxx . . $ Melder_thisThread_setRange(a8896fd0f69df779). (integercxx . . $ integer# firstElement, integercxx . . $ integer# lastElement); |
| 364 | |
| 365 | void Melder_thisThread_setCurrentElementcxx . . $ Melder_thisThread_setCurrentElement(1624ee8275b10bda). (integercxx . . $ integer# currentElement); |
| 366 | |
| 367 | double Melder_thisThread_estimateProgresscxx . . $ Melder_thisThread_estimateProgress(31fa7155c10fdd13). (); |
| 368 | |
| 369 | /* End of file MelderThread.h */ |
| 370 | #endif |