| 1 | /*!\file: LaunchThread.cpp
|
|---|
| 2 | * \brief launch thread in a generic way, covering single and multi-threaded cases
|
|---|
| 3 | * This routine attempts to simplify management of multi-threading. When multi-threadeing
|
|---|
| 4 | * is not requested (serial run), LaunchThread will just call the function (provided in argument
|
|---|
| 5 | * list), nothing fancy there. If multi-threading is requested, LaunchThread will launch the
|
|---|
| 6 | * function on multiple threads (num_threads of them), and provide these functions with the
|
|---|
| 7 | * local data they need (folded in the "gate" structure) + the thread id + the number of threads
|
|---|
| 8 | * All this info is collected in the pthread_handle structure.
|
|---|
| 9 | */
|
|---|
| 10 |
|
|---|
| 11 | #ifdef HAVE_CONFIG_H
|
|---|
| 12 | #include <config.h>
|
|---|
| 13 | #else
|
|---|
| 14 | #error "Cannot compile with HAVE_CONFIG_H symbol! run configure first!"
|
|---|
| 15 | #endif
|
|---|
| 16 |
|
|---|
| 17 | #ifdef _MULTITHREADING_
|
|---|
| 18 | #include <pthread.h>
|
|---|
| 19 | #endif
|
|---|
| 20 |
|
|---|
| 21 | #include "./issm_threads.h"
|
|---|
| 22 | #include "../Alloc/alloc.h"
|
|---|
| 23 | #include "../Exceptions/exceptions.h"
|
|---|
| 24 | #include "../../include/include.h"
|
|---|
| 25 |
|
|---|
| 26 | void LaunchThread(void* function(void*), void* gate,int num_threads){
|
|---|
| 27 |
|
|---|
| 28 | #ifdef _MULTITHREADING_
|
|---|
| 29 | int i;
|
|---|
| 30 | int* status=NULL;
|
|---|
| 31 |
|
|---|
| 32 | pthread_t* threads=NULL;
|
|---|
| 33 | pthread_handle* handles=NULL;
|
|---|
| 34 |
|
|---|
| 35 | /*dynamically allocate: */
|
|---|
| 36 | threads=(pthread_t*)xmalloc(num_threads*sizeof(pthread_t));
|
|---|
| 37 | handles=(pthread_handle*)xmalloc(num_threads*sizeof(pthread_handle));
|
|---|
| 38 |
|
|---|
| 39 | for(i=0;i<num_threads;i++){
|
|---|
| 40 | handles[i].gate=gate;
|
|---|
| 41 | handles[i].id=i;
|
|---|
| 42 | handles[i].num=num_threads;
|
|---|
| 43 | }
|
|---|
| 44 |
|
|---|
| 45 | for(i=0;i<num_threads;i++){
|
|---|
| 46 |
|
|---|
| 47 | if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
|
|---|
| 48 | _error_(" pthread_create error");
|
|---|
| 49 | }
|
|---|
| 50 | }
|
|---|
| 51 | for(i=0;i<num_threads;i++){
|
|---|
| 52 | if(pthread_join(threads[i],(void**)&status)){
|
|---|
| 53 | _error_(" pthread_join error");
|
|---|
| 54 | }
|
|---|
| 55 | }
|
|---|
| 56 |
|
|---|
| 57 | /*Free ressources:*/
|
|---|
| 58 | xfree((void**)&threads);
|
|---|
| 59 | xfree((void**)&handles);
|
|---|
| 60 |
|
|---|
| 61 | #else
|
|---|
| 62 | pthread_handle handle;
|
|---|
| 63 | handle.gate=gate;
|
|---|
| 64 | handle.id=0;
|
|---|
| 65 | handle.num=1;
|
|---|
| 66 |
|
|---|
| 67 | function((void*)&handle);
|
|---|
| 68 | #endif
|
|---|
| 69 | }
|
|---|