1 // SUMMARY : Threads for Linux and Microsoft Win32
2 // USAGE :
3 // ORG :
4 // AUTHOR : Antoine Le Hyaric / F. Hecht
5 // E-MAIL : lehyaric@ann.jussieu.fr
6
7 // This file is part of Freefem++
8 //
9 // Freefem++ is free software; you can redistribute it and/or modify
10 // it under the terms of the GNU Lesser General Public License as published by
11 // the Free Software Foundation; either version 2.1 of the License, or
12 // (at your option) any later version.
13 //
14 // Freefem++ is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 // GNU Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public License
20 // along with Freefem++; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22
23 // Frederic Hecht .
24
25 #include <cassert>
26 #include <string>
27 #include <cerrno>
28 #include <cstring>
29 #include <iostream>
30 #include <cstdlib>
31 using namespace std;
32
33 #define ERROR_FF(msg) (cerr << msg<<endl, assert(0), exit(1))
34
35 #include "ffthreads.hpp"
36
37 #ifdef __MINGW32__
38 #include <process.h>
39 #else
40 #include <signal.h>
41 #endif
42
43
44 Thread::Id Thread::Start(THREADFUNC(f,),Thread::Parm p){
45 Id tid;
46 #ifdef __MINGW32__
47 unsigned ThreadId;
48 tid = (HANDLE) _beginthreadex(NULL,0,f,p,0,&ThreadId);
49 if(tid == NULL) ERROR_FF("Thread::Start: Thread could not be created");
50 #else
51 int R = pthread_create(&tid,NULL,f,p);
52 if(R != 0) ERROR_FF("Thread::Start: Thread could not be created");
53 #endif
54 return tid;
55 }
56
Wait(Thread::Id tid)57 void Thread::Wait(Thread::Id tid){
58 #ifdef __MINGW32__
59 DWORD R = WaitForSingleObject(tid,INFINITE);
60 if(R == WAIT_FAILED) ERROR_FF("Thread::Wait" " -- Wait failed");
61 CloseHandle(tid);
62 #else
63 int R=pthread_join(tid,NULL);
64 if(R!=0) ERROR_FF("Thread::Wait: Wait failed");
65 #endif
66 }
67
Exit()68 void Thread::Exit(){
69 #ifdef __MINGW32__
70 _endthreadex(0);
71 #else
72 pthread_exit(NULL); // No test: returns void.
73 #endif
74 }
75
Kill(Thread::Id tid)76 void Thread::Kill(Thread::Id tid){
77 #ifdef __MINGW32__
78 if(TerminateThread(tid,0) == 0)
79 ERROR_FF("Thread::Kill: Thread not killed");
80 #else
81 if(pthread_kill(tid,SIGINT)!=0)
82 ERROR_FF("Thread::Kill: Thread not killed");
83 #endif
84 }
85
Current()86 Thread::Id Thread::Current(){
87 #ifdef __MINGW32__
88 return GetCurrentThread();
89 #else
90 return pthread_self();
91 #endif
92 }
93