ffead.server.doc
Thread.cpp
1 /*
2  Copyright 2009-2012, Sumeet Chhetri
3 
4  Licensed under the Apache License, Version 2.0 (the "License");
5  you may not use this file except in compliance with the License.
6  You may obtain a copy of the License at
7 
8  http://www.apache.org/licenses/LICENSE-2.0
9 
10  Unless required by applicable law or agreed to in writing, software
11  distributed under the License is distributed on an "AS IS" BASIS,
12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  See the License for the specific language governing permissions and
14  limitations under the License.
15 */
16 /*
17  * Thread.cpp
18  *
19  * Created on: 10-Aug-2012
20  * Author: sumeetc
21  */
22 
23 #include "Thread.h"
24 using namespace std;
25 
26 void* Thread::_service(void* arg)
27 {
28  ThreadFunctor* threadFunctor = (ThreadFunctor*)arg;
29  void* ret = threadFunctor->f(threadFunctor->arg);
30  pthread_exit(NULL);
31  return ret;
32 }
33 
34 Thread::Thread(ThreadFunc f, void* arg) {
35  this->threadFunctor = new ThreadFunctor();
36  this->threadFunctor->f = f;
37  this->threadFunctor->arg = arg;
38  pthread_mutex_init(&mut, NULL);
39  pthread_cond_init(&cond, NULL);
40 }
41 
42 Thread::~Thread() {
43  //pthread_join(pthread, NULL);
44  pthread_mutex_destroy(&mut);
45  pthread_cond_destroy(&cond);
46 }
47 
48 void Thread::join() {
49  if(pthread_join(pthread, NULL)) {
50  throw "Error in join for pthread";
51  }
52 }
53 
54 void Thread::nSleep(long nanos) {
55  struct timespec req={0},rem={0};
56  req.tv_sec = 0;
57  req.tv_nsec = nanos;
58  int ret = nanosleep(&req, &rem);
59  if(ret==-1)
60  {
61  struct timespec temp_rem;
62  ret = nanosleep(&req, &temp_rem);
63  }
64 }
65 
66 void Thread::uSleep(long micros) {
67  usleep(micros);
68 }
69 
70 void Thread::mSleep(long milis) {
71  usleep(milis*1000);
72 }
73 
74 void Thread::sSleep(long seconds) {
75  sleep(seconds);
76 }
77 
78 void Thread::wait() {
79  pthread_mutex_lock(&mut);
80  pthread_cond_wait(&cond, &mut);
81  pthread_mutex_unlock(&mut);
82 }
83 
84 void Thread::execute() {
85  if(pthread_create(&pthread, NULL, _service, this->threadFunctor)) {
86  throw "Error Creating pthread";
87  }
88 }
89 
90 void Thread::interrupt() {
91  pthread_mutex_lock(&mut);
92  pthread_cond_broadcast(&cond);
93  pthread_mutex_unlock(&mut);
94 }