source: issm/trunk-jpl/src/c/shared/Threads/LaunchThread.cpp@ 14917

Last change on this file since 14917 was 14917, checked in by Eric.Larour, 12 years ago

CHG: got rid of the include/include.h headere file, finally :)

File size: 2.0 KB
Line 
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 "../MemOps/MemOps.h"
23#include "../Exceptions/exceptions.h"
24
25void LaunchThread(void* function(void*), void* gate,int num_threads){
26
27 #ifdef _MULTITHREADING_
28 int i;
29 int *status = NULL;
30 pthread_t *threads = NULL;
31 pthread_handle *handles = NULL;
32
33 /*check number of threads*/
34 if(num_threads<1) _error_("number of threads must be at least 1");
35 if(num_threads>2000) _error_("number of threads seems to be too high ("<<num_threads<<">2000)");
36
37 /*dynamically allocate: */
38 threads=xNew<pthread_t>(num_threads);
39 handles=xNew<pthread_handle>(num_threads);
40
41 for(i=0;i<num_threads;i++){
42 handles[i].gate=gate;
43 handles[i].id=i;
44 handles[i].num=num_threads;
45 }
46 for(i=0;i<num_threads;i++){
47
48 if(pthread_create(threads+i,NULL,function,(void*)(handles+i))){
49 _error_("pthread_create error");
50 }
51 }
52 for(i=0;i<num_threads;i++){
53 if(pthread_join(threads[i],(void**)&status)){
54 _error_("pthread_join error");
55 }
56 }
57
58 /*Free ressources:*/
59 xDelete<pthread_t>(threads);
60 xDelete<pthread_handle>(handles);
61
62 #else
63 pthread_handle handle;
64 handle.gate=gate;
65 handle.id=0;
66 handle.num=1;
67
68 function((void*)&handle);
69 #endif
70}
Note: See TracBrowser for help on using the repository browser.