| 1 | /* Simple master/worker data parallelization using POSIX threads. |
| 2 | * |
| 3 | * The master assigns independent work chunks to workers. The master |
| 4 | * blocks until all the workers have started, then tells the workers |
| 5 | * to go. Meanwhile, workers block as they start, waiting for the go |
| 6 | * signal. The workers do their work, and exit their threads. The |
| 7 | * master blocks while it waits for them all to finish and exit. |
| 8 | * |
| 9 | * [xref H14/104 for detailed analysis of Farrar's thread synch |
| 10 | * strategy] |
| 11 | * |
| 12 | * Contents: |
| 13 | * 1. The <ESL_THREADS> object: a gang of workers. |
| 14 | * 2. Determining thread number to use. |
| 15 | * 3. Examples. |
| 16 | */ |
| 17 | #include <esl_config.h> |
| 18 | |
| 19 | #ifdef HAVE_PTHREAD |
| 20 | |
| 21 | #include <stdio.h> |
| 22 | #include <stdlib.h> |
| 23 | #include <string.h> |
| 24 | #include <pthread.h> |
| 25 | |
| 26 | #ifdef HAVE_UNISTD_H |
| 27 | #include <unistd.h> // includes sysconf() and its constants |
| 28 | #endif |
| 29 | #ifdef HAVE_SYS_TYPES_H |
| 30 | #include <sys/types.h> |
| 31 | #endif |
| 32 | |
| 33 | #include "easel.h" |
| 34 | #include "esl_threads.h" |
| 35 | |
| 36 | |
| 37 | /***************************************************************** |
| 38 | *# 1. The <ESL_THREADS> object: a gang of workers. |
| 39 | *****************************************************************/ |
| 40 | |
| 41 | /* Function: esl_threads_Create() |
| 42 | * Synopsis: Create a threads object. |
| 43 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 44 | * |
| 45 | * Purpose: Creates an <ESL_THREADS> object, for organizing |
| 46 | 8 a bunch of worker threads that will all run |
| 47 | * the worker function <fnptr>. This object is a shell |
| 48 | * for now; the worker threads themselves are |
| 49 | * created individually with <esl_threads_AddThread()>. |
| 50 | * |
| 51 | * Returns: ptr to the new <ESL_THREADS> object. |
| 52 | * |
| 53 | * Throws: <NULL> on allocation or initialization failure. |
| 54 | */ |
| 55 | ESL_THREADS * |
| 56 | esl_threads_Create(void (*fnptr)(void *)) |
| 57 | { |
| 58 | ESL_THREADS *obj = NULL; |
| 59 | int status; |
| 60 | |
| 61 | ESL_ALLOC(obj, sizeof(ESL_THREADS)); |
| 62 | |
| 63 | obj->threadCount = 0; |
| 64 | obj->threadId = NULL; |
| 65 | obj->data = NULL; |
| 66 | obj->startThread = 0; |
| 67 | obj->func = fnptr; |
| 68 | |
| 69 | if (pthread_mutex_init(&obj->startMutex, NULL) != 0) ESL_XEXCEPTION(eslESYS, "mutex init failed"); |
| 70 | if (pthread_cond_init (&obj->startCond, NULL) != 0) ESL_XEXCEPTION(eslESYS, "cond init failed"); |
| 71 | return obj; |
| 72 | |
| 73 | ERROR: |
| 74 | return NULL; |
| 75 | } |
| 76 | |
| 77 | /* Function: esl_threads_Destroy() |
| 78 | * Synopsis: Destroys an <ESL_THREADS> object. |
| 79 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 80 | * |
| 81 | * Purpose: Frees an <ESL_THREADS> object. |
| 82 | * |
| 83 | * The caller routine must first free the |
| 84 | * contents of each <obj->data[]>. |
| 85 | * |
| 86 | * Returns: void |
| 87 | */ |
| 88 | void |
| 89 | esl_threads_Destroy(ESL_THREADS *obj) |
| 90 | { |
| 91 | if (obj == NULL) return; |
| 92 | |
| 93 | if (obj->threadId != NULL) free(obj->threadId); |
| 94 | if (obj->data != NULL) free(obj->data); |
| 95 | pthread_mutex_destroy(&obj->startMutex); |
| 96 | pthread_cond_destroy (&obj->startCond); |
| 97 | free(obj); |
| 98 | return; |
| 99 | } |
| 100 | |
| 101 | /* Function: esl_threads_AddThread() |
| 102 | * Synopsis: Add a worker thread to the <ESL_THREADS> object. |
| 103 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 104 | * |
| 105 | * Purpose: Create a new worker thread for the <ESL_THREADS> object, |
| 106 | * assigning it the work unit pointed to by <data>. |
| 107 | * |
| 108 | * The caller remains responsible for any memory allocated |
| 109 | * to <data>; the <ESL_THREADS> object will only manage |
| 110 | * a copy of a pointer to <data>. |
| 111 | * |
| 112 | * Only the master calls this, while it's initializing the |
| 113 | * workers; it calls _WaitForStart() after it's done adding |
| 114 | * worker threads. |
| 115 | * |
| 116 | * Each worker thread starts immediately, and is supposed |
| 117 | * to call _Started() to block soon after it starts, and |
| 118 | * tell the master it's ready and waiting. |
| 119 | * |
| 120 | * Returns: <eslOK> on success. |
| 121 | * |
| 122 | * Throws: <eslEMEM> on allocation failure. |
| 123 | * <eslESYS> if thread creation fails. |
| 124 | * <eslEINVAL> if something's wrong with the <obj>. |
| 125 | */ |
| 126 | int |
| 127 | esl_threads_AddThread(ESL_THREADS *obj, void *data) |
| 128 | { |
| 129 | int status; |
| 130 | void *p; |
| 131 | |
| 132 | if (obj == NULL) ESL_EXCEPTION(eslEINVAL, "Invalid thread object"); |
| 133 | |
| 134 | /* allocate inside the ESL_THREADS object to hold another worker */ |
| 135 | ESL_RALLOC(obj->threadId, p, sizeof(pthread_t) * (obj->threadCount+1)); |
| 136 | ESL_RALLOC(obj->data, p, sizeof(void *) * (obj->threadCount+1)); |
| 137 | |
| 138 | obj->data[obj->threadCount] = data; |
| 139 | if (pthread_create(&(obj->threadId[obj->threadCount]), NULL, (void *(*)(void *)) obj->func, obj) != 0) ESL_EXCEPTION(eslESYS, "thread creation failed"); |
| 140 | obj->threadCount++; |
| 141 | return eslOK; |
| 142 | |
| 143 | ERROR: |
| 144 | return status; |
| 145 | } |
| 146 | |
| 147 | /* Function: esl_threads_GetWorkerCount() |
| 148 | * Synopsis: Return the total number of worker threads. |
| 149 | * Incept: SRE, Fri Aug 21 13:22:52 2009 [Janelia] |
| 150 | * |
| 151 | * Purpose: Returns the total number of worker threads. |
| 152 | * |
| 153 | * This should only be called in the master after all the |
| 154 | * _AddThread() calls are done, or in a worker after the |
| 155 | * master's go signal has been received; then this is the |
| 156 | * number of parallel workers. |
| 157 | */ |
| 158 | int |
| 159 | esl_threads_GetWorkerCount(ESL_THREADS *obj) |
| 160 | { |
| 161 | return obj->threadCount; |
| 162 | } |
| 163 | |
| 164 | |
| 165 | /* Function: esl_threads_WaitForStart() |
| 166 | * Synopsis: Blocks master until all workers have started. |
| 167 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 168 | * |
| 169 | * Purpose: Make the master thread wait until all the worker threads have |
| 170 | * started. When all the worker threads have started and |
| 171 | * are blocking at the start mutex, release them. |
| 172 | * |
| 173 | * Returns: <eslOK> on success. |
| 174 | * |
| 175 | * Throws: <eslESYS> if thread synchronization fails somewhere. |
| 176 | * <eslEINVAL> if something is awry with <obj>. |
| 177 | */ |
| 178 | int |
| 179 | esl_threads_WaitForStart(ESL_THREADS *obj) |
| 180 | { |
| 181 | if (obj == NULL) ESL_EXCEPTION(eslEINVAL, "Invalid thread object"); |
| 182 | |
| 183 | if (pthread_mutex_lock (&obj->startMutex) != 0) ESL_EXCEPTION(eslESYS, "mutex lock failed"); |
| 184 | |
| 185 | /* wait for all worker threads to start */ |
| 186 | while (obj->startThread < obj->threadCount) { |
| 187 | if (pthread_cond_wait(&obj->startCond, &obj->startMutex) != 0) ESL_EXCEPTION(eslESYS, "wait cond failed"); |
| 188 | } |
| 189 | |
| 190 | /* release all the worker threads */ |
| 191 | obj->startThread = 0; |
| 192 | if (pthread_cond_broadcast(&obj->startCond) != 0) ESL_EXCEPTION(eslESYS, "cond broadcast failed"); |
| 193 | if (pthread_mutex_unlock (&obj->startMutex) != 0) ESL_EXCEPTION(eslESYS, "mutex unlock failed"); |
| 194 | return eslOK; |
| 195 | } |
| 196 | |
| 197 | /* Function: esl_threads_WaitForFinish() |
| 198 | * Synopsis: Blocks master until all workers have completed. |
| 199 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 200 | * |
| 201 | * Purpose: Block the master thread until all the worker threads have |
| 202 | * completed. As each worker completes, remove it from the |
| 203 | * <obj>. |
| 204 | * |
| 205 | * Upon exit, the <obj> is returned to the same (empty) |
| 206 | * state it was in after it was created. It may be reused |
| 207 | * for a new problem by adding new workers. |
| 208 | * |
| 209 | * Returns: <eslOK> on success. |
| 210 | * |
| 211 | * Throws: <eslESYS> if thread synchronization fails somewhere. |
| 212 | * <eslEINVAL> if something is awry with <obj>. |
| 213 | */ |
| 214 | int |
| 215 | esl_threads_WaitForFinish(ESL_THREADS *obj) |
| 216 | { |
| 217 | int w; |
| 218 | |
| 219 | if (obj == NULL) ESL_EXCEPTION(eslEINVAL, "Invalid thread object"); |
| 220 | |
| 221 | /* wait for all worker threads to complete */ |
| 222 | for (w = obj->threadCount-1; w >= 0; w--) |
| 223 | if (pthread_join(obj->threadId[w], NULL) != 0) ESL_EXCEPTION(eslESYS, "pthread join failed"); |
| 224 | obj->threadCount = 0; // can't touch threadCount until workers are all finished, because they may be using it. |
| 225 | |
| 226 | return eslOK; |
| 227 | } |
| 228 | |
| 229 | /* Function: esl_threads_Started() |
| 230 | * Synopsis: Blocks worker until master gives the start signal. |
| 231 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 232 | * |
| 233 | * Purpose: Block a worker thread until master sees that all workers |
| 234 | * have started and gives the start signal. Assign the worker |
| 235 | * a unique number (0..nworkers-1), and return it in |
| 236 | * <*ret_workeridx>. The worker uses this index to |
| 237 | * retrieve its work units. |
| 238 | * |
| 239 | * Returns: <eslOK> on success. |
| 240 | * |
| 241 | * Throws: <eslESYS> if thread synchronization fails somewhere. |
| 242 | * <eslEINVAL> if something is awry with <obj>. |
| 243 | */ |
| 244 | int |
| 245 | esl_threads_Started(ESL_THREADS *obj, int *ret_workeridx) |
| 246 | { |
| 247 | int w; |
| 248 | pthread_t threadId; |
| 249 | int status; |
| 250 | |
| 251 | if (obj == NULL) ESL_XEXCEPTION(eslEINVAL, "Invalid thread object"); |
| 252 | if (pthread_mutex_lock (&obj->startMutex) != 0) ESL_XEXCEPTION(eslESYS, "mutex lock failed"); |
| 253 | |
| 254 | /* signal that we're started */ |
| 255 | obj->startThread++; |
| 256 | if (pthread_cond_broadcast (&obj->startCond) != 0) ESL_XEXCEPTION(eslESYS, "cond broadcast failed"); |
| 257 | |
| 258 | /* the logic here is a little inelegant, but it's because we're |
| 259 | * using the same start mutex/condition for both the worker->master |
| 260 | * started signal and the master->worker go signal, so maybe it's |
| 261 | * elegant from that perspective. What's happening is that each time |
| 262 | * a worker starts, it *broadcasts* the start condition. It's |
| 263 | * intended for the master; if the master sees that startThread == |
| 264 | * threadCount it knows that all workers have started, and it can |
| 265 | * tell them to go. But since it's broadcast, and workers are also |
| 266 | * waiting for the "go" start condition (below), workers will wake |
| 267 | * up below; but they see that startThread > 0, so they go back to |
| 268 | * sleep. |
| 269 | * |
| 270 | * Once we finish starting threads, the master sets startThread back |
| 271 | * to 0, then broadcasts the start condition again. Now all the |
| 272 | * workers wake up below, and see startThread=0, break their while |
| 273 | * loop and proceed. |
| 274 | * |
| 275 | * So the cost is a lot of unnecessary worker-waking while we're |
| 276 | * really just sending a 1:1 signal from a newly started worker to |
| 277 | * the master. We could instead use two different "started" and "go" |
| 278 | * mutexes/conditions. |
| 279 | * |
| 280 | * [SRE note added; xref H14/104] |
| 281 | */ |
| 282 | |
| 283 | /* wait for the master's go signal to start the calculations */ |
| 284 | while (obj->startThread) { |
| 285 | if (pthread_cond_wait(&obj->startCond, &obj->startMutex) != 0) ESL_XEXCEPTION(eslESYS, "cond wait failed"); |
| 286 | } |
| 287 | |
| 288 | if (pthread_mutex_unlock (&obj->startMutex) != 0) ESL_XEXCEPTION(eslESYS, "mutex unlock failed"); |
| 289 | |
| 290 | /* Figure out the worker's index */ |
| 291 | threadId = pthread_self(); |
| 292 | for (w = 0; w < obj->threadCount; w++) // threadCount is stable until thread terminates. |
| 293 | if (pthread_equal(threadId, obj->threadId[w])) break; |
| 294 | if (w == obj->threadCount) ESL_XEXCEPTION(eslESYS, "thread not registered"); |
| 295 | |
| 296 | *ret_workeridx = w; |
| 297 | return eslOK; |
| 298 | |
| 299 | ERROR: |
| 300 | *ret_workeridx = 0; |
| 301 | return status; |
| 302 | } |
| 303 | |
| 304 | |
| 305 | /* Function: esl_threads_GetData() |
| 306 | * Synopsis: Return the data associated with this thread. |
| 307 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 308 | * |
| 309 | * Purpose: Return the data pointer associated with the worker thread |
| 310 | * <workeridx>. The data pointer was set by the |
| 311 | * <esl_threads_AddThread()> function. |
| 312 | * |
| 313 | * Returns: void * |
| 314 | */ |
| 315 | void * |
| 316 | esl_threads_GetData(ESL_THREADS *obj, int workeridx) |
| 317 | { |
| 318 | return obj->data[workeridx]; |
| 319 | } |
| 320 | |
| 321 | |
| 322 | /* Function: esl_threads_Finished() |
| 323 | * Synopsis: Terminate the thread. |
| 324 | * Incept: MSF, Thu Jun 18 11:51:39 2009 |
| 325 | * |
| 326 | * Purpose: Terminate a worker thread. |
| 327 | * This is currently a no-op, serving as |
| 328 | * a placeholder in case we eventually need |
| 329 | * any cleanup. |
| 330 | * |
| 331 | * Returns: <eslOK> on success. |
| 332 | */ |
| 333 | int |
| 334 | esl_threads_Finished(ESL_THREADS *obj, int workeridx) |
| 335 | { |
| 336 | return eslOK; |
| 337 | } |
| 338 | |
| 339 | |
| 340 | /***************************************************************** |
| 341 | * 2. Determining thread number to use |
| 342 | *****************************************************************/ |
| 343 | |
| 344 | /* Function: esl_threads_CPUCount() |
| 345 | * Synopsis: Figure out how many cores the machine has available. |
| 346 | * Incept: SRE, Wed Aug 19 11:31:24 2009 [Janelia] |
| 347 | * |
| 348 | * Purpose: Determine the number of logical processors on this |
| 349 | * machine; return that number in <*ret_ncpu>. |
| 350 | * |
| 351 | * The number of available processors is found by |
| 352 | * <sysconf(_SC_NPROCESSORS_ONLN)>, a POSIX standard. If |
| 353 | * sysconf() is somehow unavailable, <*ret_ncpu> is quietly |
| 354 | * just set to 1. |
| 355 | * |
| 356 | * This is the number of logical processors, not physical |
| 357 | * processors. On systems with hyperthreading, the number |
| 358 | * of logical processors is more than the number of |
| 359 | * physical cpus. It may or may not be a good thing to |
| 360 | * spawn more threads than physical processors. |
| 361 | * |
| 362 | * Args: ret_ncpu - RETURN: number of logical cores |
| 363 | * |
| 364 | * Returns: <eslOK> on success. |
| 365 | * |
| 366 | * Throws: (no abnormal error conditions) |
| 367 | * |
| 368 | * Xref: J5/68; H14/5. |
| 369 | */ |
| 370 | int |
| 371 | esl_threads_CPUCount(int *ret_ncpu) |
| 372 | { |
| 373 | int ncpu = 1; |
| 374 | |
| 375 | #if defined (HAVE_SYSCONF) && defined (_SC_NPROCESSORS_ONLN) // POSIX standard |
| 376 | ncpu = sysconf(_SC_NPROCESSORS_ONLN); |
| 377 | #elif defined (HAVE_SYSCONF) && defined (_SC_NPROC_ONLN) // Silicon Graphics IRIX used to be this way |
| 378 | ncpu = sysconf(_SC_NPROC_ONLN); // Don't use sysctl() as a fallback. Linux/gcc deprecated it. [H14/5] |
| 379 | #endif |
| 380 | if (ncpu < 1) ncpu = 1; // silently ignore any sysconf() problem, including nonexistence; fall back to 1 core. |
| 381 | |
| 382 | *ret_ncpu = ncpu; |
| 383 | return eslOK; |
| 384 | } |
| 385 | |
| 386 | |
| 387 | /* Function: esl_threads_GetCPUCount() |
| 388 | * Synopsis: Returns the number of CPU cores on machine. |
| 389 | * Incept: SRE, Mon Aug 21 08:52:29 2017 |
| 390 | * |
| 391 | * Purpose: Identical to <esl_threads_CPUCount()>, except |
| 392 | * it directly returns the result. |
| 393 | */ |
| 394 | int |
| 395 | esl_threads_GetCPUCount(void) |
| 396 | { |
| 397 | static int ncpu = -1; // so we only make system calls once. |
| 398 | if (ncpu == -1) esl_threads_CPUCount(&ncpu); |
| 399 | return ncpu; |
| 400 | } |
| 401 | |
| 402 | |
| 403 | /***************************************************************** |
| 404 | * 3. Example |
| 405 | *****************************************************************/ |
| 406 | |
| 407 | #ifdef eslTHREADS_EXAMPLE |
| 408 | #include "easel.h" |
| 409 | #include "esl_threads.h" |
| 410 | |
| 411 | static void |
| 412 | worker_thread(void *data) |
| 413 | { |
| 414 | ESL_THREADS *thr = (ESL_THREADS *) data; |
| 415 | char *s = NULL; |
| 416 | int w; |
| 417 | |
| 418 | esl_threads_Started(thr, &w); |
| 419 | |
| 420 | s = (char *) esl_threads_GetData(thr, w); |
| 421 | printf("worker thread %d receives: %s\n", w, s); |
| 422 | |
| 423 | esl_threads_Finished(thr, w); |
| 424 | return; |
| 425 | } |
| 426 | |
| 427 | int |
| 428 | main(void) |
| 429 | { |
| 430 | ESL_THREADS *thr = NULL; |
| 431 | int ncpu = 8; |
| 432 | int i; |
| 433 | char **work = NULL; |
| 434 | |
| 435 | work = malloc(sizeof(char *) * ncpu); |
| 436 | for (i = 0; i < ncpu; i++) |
| 437 | esl_sprintf(&(work[i]), "work packet %d", i); |
| 438 | |
| 439 | thr = esl_threads_Create(&worker_thread); |
| 440 | |
| 441 | for (i = 0; i < ncpu; i++) |
| 442 | esl_threads_AddThread(thr, (void *) work[i]); |
| 443 | |
| 444 | esl_threads_WaitForStart (thr); |
| 445 | /* The worker threads now run their work. */ |
| 446 | esl_threads_WaitForFinish(thr); |
| 447 | esl_threads_Destroy(thr); |
| 448 | for (i = 0; i < ncpu; i++) free(work[i]); |
| 449 | free(work); |
| 450 | return eslOK; |
| 451 | } |
| 452 | #endif /*eslTHREADS_EXAMPLE*/ |
| 453 | |
| 454 | |
| 455 | #ifdef eslTHREADS_EXAMPLE2 |
| 456 | #include "easel.h" |
| 457 | #include "esl_threads.h" |
| 458 | |
| 459 | /* gcc --std=gnu99 -g -Wall -pthread -o esl_threads_example2 -I. -DeslTHREADS_EXAMPLE2 esl_threads.c easel.c */ |
| 460 | int |
| 461 | main(void) |
| 462 | { |
| 463 | int ncpu; |
| 464 | |
| 465 | esl_threads_CPUCount(&ncpu); |
| 466 | printf("Processors: %d\n", ncpu); |
| 467 | |
| 468 | return eslOK; |
| 469 | } |
| 470 | #endif /*eslTHREADS_EXAMPLE2*/ |
| 471 | #endif /*HAVE_PTHREAD*/ |
| 472 | |
| 473 |