10 Thread::Thread(int synchronous, int realtime, int autodelete)
12 this->synchronous = synchronous;
13 this->realtime = realtime;
14 this->autodelete = autodelete;
25 void* Thread::entrypoint(void *parameters)
27 Thread *thread = (Thread*)parameters;
29 // allow thread to be cancelled at any point during a region where it is enabled.
30 pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, 0);
31 // Disable cancellation by default.
32 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, 0);
33 thread->cancel_enabled = 0;
35 // Set realtime here seince it doesn't work in start
36 if(thread->realtime && getuid() == 0)
38 struct sched_param param =
42 if(pthread_setschedparam(thread->tid, SCHED_RR, ¶m) < 0)
43 perror("Thread::entrypoint pthread_attr_setschedpolicy");
48 thread->thread_running = 0;
50 if(thread->autodelete && !thread->synchronous) delete thread;
57 struct sched_param param;
59 pthread_attr_init(&attr);
63 // Inherit realtime from current thread the easy way.
64 if(!realtime) realtime = calculate_realtime();
67 if(!synchronous) pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
69 if(realtime && getuid() == 0)
71 if(pthread_attr_setschedpolicy(&attr, SCHED_RR) < 0)
72 perror("Thread::start pthread_attr_setschedpolicy");
73 param.sched_priority = 50;
74 if(pthread_attr_setschedparam(&attr, ¶m) < 0)
75 perror("Thread::start pthread_attr_setschedparam");
79 if(pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED) < 0)
80 perror("Thread::start pthread_attr_setinheritsched");
83 pthread_create(&tid, &attr, Thread::entrypoint, this);
87 int Thread::end(pthread_t tid) // need to join after this if synchronous
96 int Thread::end() // need to join after this if synchronous
104 if(tid_valid) pthread_cancel(tid);
113 int Thread::join() // join this thread
118 result = pthread_join(tid, 0);
124 // Don't execute anything after this.
125 if(autodelete && synchronous) delete this;
129 int Thread::enable_cancel()
132 pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
136 int Thread::disable_cancel()
138 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
143 int Thread::get_cancel_enabled()
145 return cancel_enabled;
148 int Thread::exit_thread()
160 int Thread::suspend_thread()
162 if(tid_valid) pthread_kill(tid, SIGSTOP);
166 int Thread::continue_thread()
168 if(tid_valid) pthread_kill(tid, SIGCONT);
172 int Thread::running()
174 return thread_running;
177 int Thread::set_synchronous(int value)
179 this->synchronous = value;
183 int Thread::set_realtime(int value)
185 this->realtime = value;
189 int Thread::set_autodelete(int value)
191 this->autodelete = value;
195 int Thread::get_autodelete()
200 int Thread::get_synchronous()
205 int Thread::calculate_realtime()
207 //printf("Thread::calculate_realtime %d %d\n", getpid(), sched_getscheduler(0));
208 return (sched_getscheduler(0) == SCHED_RR ||
209 sched_getscheduler(0) == SCHED_FIFO);
212 int Thread::get_realtime()
217 int Thread::get_tid()