12 Thread::Thread(int synchronous, int realtime, int autodelete)
14 this->synchronous = synchronous;
15 this->realtime = realtime;
16 this->autodelete = autodelete;
27 void* Thread::entrypoint(void *parameters)
29 Thread *thread = (Thread*)parameters;
31 // allow thread to be cancelled at any point during a region where it is enabled.
32 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
33 // Disable cancellation by default.
34 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
35 thread->cancel_enabled = 0;
37 // Set realtime here seince it doesn't work in start
38 if(thread->realtime && getuid() == 0)
40 struct sched_param param =
44 if(pthread_setschedparam(thread->tid, SCHED_RR, ¶m) < 0)
45 perror("Thread::entrypoint pthread_attr_setschedpolicy");
50 thread->thread_running = 0;
52 if(thread->autodelete && !thread->synchronous) delete thread;
59 struct sched_param param;
61 pthread_attr_init(&attr);
65 // Inherit realtime from current thread the easy way.
66 if(!realtime) realtime = calculate_realtime();
69 if(!synchronous) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
71 if(realtime && getuid() == 0)
73 if(pthread_attr_setschedpolicy(&attr, SCHED_RR) < 0)
74 perror("Thread::start pthread_attr_setschedpolicy");
75 param.sched_priority = 50;
76 if(pthread_attr_setschedparam(&attr, ¶m) < 0)
77 perror("Thread::start pthread_attr_setschedparam");
81 if(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED) < 0)
82 perror("Thread::start pthread_attr_setinheritsched");
85 pthread_create(&tid, &attr, Thread::entrypoint, this);
89 int Thread::end(pthread_t tid) // need to join after this if synchronous
98 int Thread::end() // need to join after this if synchronous
106 if(tid_valid) pthread_cancel(tid);
115 int Thread::join() // join this thread
120 result = pthread_join(tid, 0);
126 // Don't execute anything after this.
127 if(autodelete && synchronous) delete this;
131 int Thread::enable_cancel()
134 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
138 int Thread::disable_cancel()
140 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
145 int Thread::get_cancel_enabled()
147 return cancel_enabled;
150 int Thread::exit_thread()
162 int Thread::suspend_thread()
164 if(tid_valid) pthread_kill(tid, SIGSTOP);
168 int Thread::continue_thread()
170 if(tid_valid) pthread_kill(tid, SIGCONT);
174 int Thread::running()
176 return thread_running;
179 int Thread::set_synchronous(int value)
181 this->synchronous = value;
185 int Thread::set_realtime(int value)
187 this->realtime = value;
191 int Thread::set_autodelete(int value)
193 this->autodelete = value;
197 int Thread::get_autodelete()
202 int Thread::get_synchronous()
207 int Thread::calculate_realtime()
209 //printf("Thread::calculate_realtime %d %d\n", getpid(), sched_getscheduler(0));
210 return (sched_getscheduler(0) == SCHED_RR ||
211 sched_getscheduler(0) == SCHED_FIFO);
214 int Thread::get_realtime()
219 int Thread::get_tid()