Debian Codegraph @

src/core/util_thread.cpp

raw symbols SCIP
1 /*----------------------------------------------------------------------------
2 ChucK Strongly-timed Audio Programming Language
3 Compiler, Virtual Machine, and Synthesis Engine
4
5 Copyright (c) 2003 Ge Wang and Perry R. Cook. All rights reserved.
6 http://chuck.stanford.edu/
7 http://chuck.cs.princeton.edu/
8
9 This program is free software; you can redistribute it and/or modify
10 it under the dual-license terms of EITHER the MIT License OR the GNU
11 General Public License (the latter as published by the Free Software
12 Foundation; either version 2 of the License or, at your option, any
13 later version).
14
15 This program is distributed in the hope that it will be useful and/or
16 interesting, but WITHOUT ANY WARRANTY; without even the implied warranty
17 of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 MIT Licence and/or the GNU General Public License for details.
19
20 You should have received a copy of the MIT License and the GNU General
21 Public License (GPL) along with this program; a copy of the GPL can also
22 be obtained by writing to the Free Software Foundation, Inc., 59 Temple
23 Place, Suite 330, Boston, MA 02111-1307 U.S.A.
24 -----------------------------------------------------------------------------*/
25
26 //-----------------------------------------------------------------------------
27 // name: util_thread.cpp
28 // desc: thread utilities
29 //
30 // authors: Ge Wang ([email protected] | [email protected])
31 // based on STK's Thread
32 // Perry R. Cook + Gary Scavone
33 // date: autumn 2004
34 //-----------------------------------------------------------------------------
35 #include "util_thread.h"
36 #include "util_buffers.h"
37 #include "util_platforms.h"
38 #include "chuck_errmsg.h"
39
40
41
42
43 // static instantiation
44 const size_t XWriteThread::PRODUCER_BUFFER_SIZE = 1024;
45 XWriteThread * XWriteThread::o_defaultWriteThread = NULL;
46
47
48
49
50
51 //-----------------------------------------------------------------------------
52 // name: XThread()
53 // desc: ...
54 //-----------------------------------------------------------------------------
55 XThread::XThread( )
56 {
57 thread = 0;
58 }
59
60
61
62
63 //-----------------------------------------------------------------------------
64 // name: ~XThread()
65 // desc: ...
66 //-----------------------------------------------------------------------------
67 XThread::~XThread( )
68 {
69 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
70 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
71 // can't self-terminate (much like the Terminator)
72 bool is_self_thread = (thread == pthread_self());
73 #elif defined(__PLATFORM_WINDOWS__)
74 // ignore for now
75 bool is_self_thread = false;
76 #endif
77
78 // if our thread not NULL and this destructor is NOT being called on it
79 if( thread != 0 && !is_self_thread )
80 {
81 // TODO: find an alternative for Android?
82 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
83 #if defined(__PLATFORM_APPLE__) || ( defined(__PLATFORM_LINUX__) && !defined(__ANDROID__) ) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
84 // log
85 EM_log( CK_LOG_FINER, "cancelling thread [0x%x] from [0x%x]...", getID(thread), getID(pthread_self()) );
86 pthread_cancel(thread);
87 pthread_join(thread, NULL);
88 // log
89 EM_log( CK_LOG_FINER, "joined with thread [0x%x] from [0x%x]", getID(thread), getID(pthread_self()) );
90 #elif defined(__PLATFORM_WINDOWS__)
91 // log
92 EM_log( CK_LOG_FINER, "terminating thread [0x%x] from [0x%x]...", getID(thread), (t_CKUINT)GetCurrentThreadId() );
93 TerminateThread( (HANDLE)thread, 0 );
94 #endif
95 }
96 }
97
98
99
100
101 //-----------------------------------------------------------------------------
102 // name: start()
103 // desc: ...
104 //-----------------------------------------------------------------------------
105 bool XThread::start( THREAD_FUNCTION routine, void * ptr )
106 {
107 bool result = false;
108
109 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
110 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
111 if( pthread_create( &thread, NULL, *routine, ptr ) == 0 )
112 {
113 EM_log( CK_LOG_FINER, "starting thread [0x%x] from [0x%x]...", thread, getID(pthread_self()) );
114 result = true;
115 }
116 #elif defined(__PLATFORM_WINDOWS__)
117 unsigned thread_id;
118 thread = _beginthreadex( NULL, 0, routine, ptr, 0, &thread_id );
119 if( thread )
120 {
121 EM_log( CK_LOG_FINER, "starting thread [0x%x] from [0x%x]...", thread_id, (t_CKUINT)GetCurrentThreadId() );
122 result = true;
123 }
124 #endif
125 return result;
126 }
127
128
129
130
131 //-----------------------------------------------------------------------------
132 // name: wait()
133 // desc: ...
134 //-----------------------------------------------------------------------------
135 bool XThread::wait( long milliseconds, bool cancel )
136 {
137 bool result = false;
138
139 // TODO: find an alternative for Android?
140 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
141 #if defined(__PLATFORM_APPLE__) || ( defined(__PLATFORM_LINUX__) && !defined(__ANDROID__) ) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
142 // cancel the thread?
143 if( cancel ) pthread_cancel( thread );
144 // wait for the thread to terminate
145 pthread_join( thread, NULL );
146 #elif defined(__PLATFORM_WINDOWS__)
147 DWORD timeout, retval;
148 if( milliseconds < 0 ) timeout = INFINITE;
149 else timeout = milliseconds;
150 retval = WaitForSingleObject( (HANDLE)thread, timeout );
151 if( retval == WAIT_OBJECT_0 ) {
152 CloseHandle( (HANDLE)thread );
153 thread = 0;
154 result = true;
155 }
156 #endif
157
158 return result;
159 }
160
161
162
163
164 //-----------------------------------------------------------------------------
165 // name: test()
166 // desc: ...
167 //-----------------------------------------------------------------------------
168 void XThread :: test( )
169 {
170 // TODO: find an alternative for Android?
171 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
172 #if defined(__PLATFORM_APPLE__) || ( defined(__PLATFORM_LINUX__) && !defined(__ANDROID__) ) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
173 pthread_testcancel();
174 #endif
175 }
176
177
178
179
180 //-----------------------------------------------------------------------------
181 // name: getID() | 1.5.0.4 (ge) added
182 // desc: get thread id from a thread handle
183 //-----------------------------------------------------------------------------
184 t_CKUINT XThread::getID( THREAD_HANDLE t )
185 {
186 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
187 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
188 return (t_CKUINT)t;
189 #elif defined(__PLATFORM_WINDOWS__)
190 return (t_CKUINT)GetThreadId( (HANDLE)t );
191 #endif
192 }
193
194
195
196
197 //-----------------------------------------------------------------------------
198 // name: XMutex()
199 // desc: ...
200 //-----------------------------------------------------------------------------
201 XMutex::XMutex( )
202 {
203 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
204 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
205 pthread_mutex_init(&mutex, NULL);
206 #elif defined(__PLATFORM_WINDOWS__)
207 InitializeCriticalSection(&mutex);
208 #endif
209 }
210
211
212
213
214 //-----------------------------------------------------------------------------
215 // name: XMutex()
216 // desc: ...
217 //-----------------------------------------------------------------------------
218 XMutex::~XMutex( )
219 {
220 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
221 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
222 pthread_mutex_destroy( &mutex );
223 #elif defined(__PLATFORM_WINDOWS__)
224 DeleteCriticalSection(&mutex);
225 #endif
226 }
227
228
229
230
231 //-----------------------------------------------------------------------------
232 // name: acquire()
233 // desc: ...
234 //-----------------------------------------------------------------------------
235 void XMutex::acquire( )
236 {
237 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
238 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
239 pthread_mutex_lock(&mutex);
240 #elif defined(__PLATFORM_WINDOWS__)
241 EnterCriticalSection(&mutex);
242 #endif
243 }
244
245
246
247
248 //-----------------------------------------------------------------------------
249 // name: unlock()
250 // desc: ...
251 //-----------------------------------------------------------------------------
252 void XMutex::release( )
253 {
254 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
255 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
256 pthread_mutex_unlock(&mutex);
257 #elif defined(__PLATFORM_WINDOWS__)
258 LeaveCriticalSection(&mutex);
259 #endif
260 }
261
262
263
264
265 //-----------------------------------------------------------------------------
266 // name: shared()
267 // desc: get XWriteThread shared instance
268 //-----------------------------------------------------------------------------
269 XWriteThread * XWriteThread::shared()
270 {
271 // static XWriteThread s_defaultWriteThread;
272
273 // check
274 if( o_defaultWriteThread == NULL )
275 o_defaultWriteThread = new XWriteThread();
276
277 return o_defaultWriteThread;
278 }
279
280
281
282
283 //-----------------------------------------------------------------------------
284 // name: XWriteThread()
285 // desc: constructor
286 //-----------------------------------------------------------------------------
287 XWriteThread::XWriteThread(size_t data_buffer_size, size_t msg_buffer_size)
288 :
289 m_msg_buffer(new CircularBuffer<Message>(msg_buffer_size)),
290 m_data_buffer(new FastCircularBuffer),
291 m_thread_buffer(new t_CKBYTE[data_buffer_size])
292 {
293 m_data_buffer->initialize( data_buffer_size, sizeof(char) );
294 m_thread_exit = FALSE;
295 m_thread.start( write_cb, this );
296 m_stream = NULL;
297 m_bytes_in_buffer = 0;
298 }
299
300
301
302
303 //-----------------------------------------------------------------------------
304 // name: ~XWriteThread()
305 // desc: destructor
306 //-----------------------------------------------------------------------------
307 XWriteThread::~XWriteThread()
308 {
309 CK_SAFE_DELETE( m_msg_buffer );
310 CK_SAFE_DELETE( m_data_buffer );
311 CK_SAFE_DELETE_ARRAY( m_thread_buffer );
312 }
313
314
315
316
317 //-----------------------------------------------------------------------------
318 // name: shutdown()
319 // desc: close down writer thread and delete in background
320 //-----------------------------------------------------------------------------
321 void XWriteThread::shutdown()
322 {
323 // put shutdown message into message buffer
324 Message msg;
325 msg.operation = Message::SHUTDOWN;
326 m_msg_buffer->put( msg );
327
328 // smart log push
329 SmartPushLog logPush;
330
331 // log
332 EM_log( CK_LOG_FINER, "waiting on write thread [0x%x]...", m_thread.getID() );
333 // wait on the thread
334 m_thread.wait( -1, false );
335 // log
336 EM_log( CK_LOG_FINER, "done waiting for thread [0x%x]", m_thread.getID() );
337 }
338
339
340
341
342 //-----------------------------------------------------------------------------
343 // name: fwrite()
344 // desc: ...
345 //-----------------------------------------------------------------------------
346 size_t XWriteThread::fwrite(const void * ptr, size_t size, size_t nitems, FILE * stream)
347 {
348 if(stream != m_stream)
349 flush_data_buffer();
350
351 // TODO: overflow detection
352 if( m_data_buffer->put((char*)ptr, size*nitems) == 0 )
353 {
354 EM_log( CK_LOG_HERALD, "XWriteThread::fwrite(): data buffer overflow!" );
355 }
356
357 m_bytes_in_buffer += size*nitems;
358 m_stream = stream;
359
360 if(m_bytes_in_buffer >= PRODUCER_BUFFER_SIZE)
361 flush_data_buffer();
362
363 return nitems;
364 }
365
366
367
368
369 //-----------------------------------------------------------------------------
370 // name: fseek()
371 // desc: ...
372 //-----------------------------------------------------------------------------
373 int XWriteThread::fseek(FILE *stream, long offset, int whence)
374 {
375 flush_data_buffer();
376
377 Message msg;
378 msg.file = stream;
379 msg.operation = Message::SEEK;
380 msg.seek.offset = offset;
381 msg.seek.whence = whence;
382 m_msg_buffer->put(msg);
383
384 return 0;
385 }
386
387
388
389
390 //-----------------------------------------------------------------------------
391 // name: fflush()
392 // desc: ...
393 //-----------------------------------------------------------------------------
394 int XWriteThread::fflush(FILE *stream)
395 {
396 flush_data_buffer();
397
398 Message msg;
399 msg.file = stream;
400 msg.operation = Message::FLUSH;
401 m_msg_buffer->put(msg);
402
403 return 0;
404 }
405
406
407
408
409 //-----------------------------------------------------------------------------
410 // name: fclose()
411 // desc: ...
412 //-----------------------------------------------------------------------------
413 int XWriteThread::fclose(FILE *stream)
414 {
415 flush_data_buffer();
416
417 Message msg;
418 msg.file = stream;
419 msg.operation = Message::CLOSE;
420 m_msg_buffer->put(msg);
421
422 return 0;
423 }
424
425
426
427
428 //-----------------------------------------------------------------------------
429 // name: flush_data_buffer()
430 // desc: ...
431 //-----------------------------------------------------------------------------
432 void XWriteThread::flush_data_buffer()
433 {
434 if(m_bytes_in_buffer > 0)
435 {
436 Message msg;
437 msg.file = m_stream;
438 msg.operation = Message::WRITE;
439 msg.write.data_size = m_bytes_in_buffer;
440 m_msg_buffer->put(msg);
441
442 m_bytes_in_buffer = 0;
443 }
444 }
445
446
447
448
449 //-----------------------------------------------------------------------------
450 // name: write_cb()
451 // desc: thread function
452 //-----------------------------------------------------------------------------
453 // 1.5.5.8 (ben, ge) added emscripten since it uses POSIX
454 #if defined(__PLATFORM_APPLE__) || defined(__PLATFORM_LINUX__) || defined(__WINDOWS_PTHREAD__) || defined(__PLATFORM_EMSCRIPTEN__)
455 void * XWriteThread::write_cb(void * _thiss)
456 #elif defined(__PLATFORM_WINDOWS__)
457 unsigned XWriteThread::write_cb(void * _thiss)
458 #endif
459 {
460 XWriteThread * _this = (XWriteThread *) _thiss;
461 Message msg;
462
463 while(!_this->m_thread_exit)
464 {
465 while(_this->m_msg_buffer->get(msg))
466 {
467 if(msg.operation == Message::WRITE)
468 {
469 size_t actual_size = _this->m_data_buffer->get(_this->m_thread_buffer,
470 msg.write.data_size);
471 if(actual_size != msg.write.data_size)
472 {
473 EM_log( CK_LOG_HERALD, "XWriteThread: buffered data size mismatch (%li : %li)",
474 msg.write.data_size, actual_size );
475 }
476
477 ::fwrite(_this->m_thread_buffer, 1, actual_size, msg.file);
478 }
479 else if(msg.operation == Message::SEEK)
480 {
481 ::fseek(msg.file, msg.seek.offset, msg.seek.whence);
482 }
483 else if(msg.operation == Message::FLUSH)
484 {
485 ::fflush(msg.file);
486 }
487 else if(msg.operation == Message::CLOSE)
488 {
489 ::fclose(msg.file);
490 }
491 else if(msg.operation == Message::SHUTDOWN)
492 {
493 _this->m_thread_exit = TRUE;
494 break;
495 }
496 }
497
498 ck_usleep(1000);
499 }
500
501 delete _this;
502 _thiss = _this = NULL;
503
504 return 0;
505 }
506
507
508
509
510 #ifdef __PLATFORM_APPLE__
511 t_CKINT XThreadUtil::our_priority = 85;
512 #else
513 t_CKINT XThreadUtil::our_priority = 0x7fffffff;
514 #endif
515
516
517
518
519 #if !defined(__PLATFORM_WINDOWS__) || defined(__WINDOWS_PTHREAD__)
520 //-----------------------------------------------------------------------------
521 // name: set_priority()
522 // desc: set thread priority
523 //-----------------------------------------------------------------------------
524 t_CKBOOL XThreadUtil::set_priority( CHUCK_THREAD tid, t_CKINT priority )
525 {
526 struct sched_param param;
527 int policy;
528
529 // log
530 EM_log( CK_LOG_INFO, "setting thread [0x%x] priority to: %ld...", (t_CKUINT)tid, priority );
531
532 // get for thread
533 if( pthread_getschedparam( tid, &policy, &param) )
534 return FALSE;
535
536 // pthread_attr_t attr;
537 // pthread_attr_init( &attr );
538 // pthread_attr_setinheritsched( &attr, PTHREAD_EXPLICIT_SCHED );
539
540 // policy
541 policy = SCHED_RR;
542 // priority
543 param.sched_priority = (int)priority;
544 // set for thread, pthread style
545 if( pthread_setschedparam( tid, policy, &param ) )
546 return FALSE;
547
548 // get for thread
549 if( pthread_getschedparam( tid, &policy, &param) )
550 return FALSE;
551
552 // push
553 EM_pushlog();
554 // log
555 EM_log( CK_LOG_FINE, "verifying thread priority: %ld...", param.sched_priority );
556 // pop
557 EM_poplog();
558
559 return TRUE;
560 }
561 //-----------------------------------------------------------------------------
562 // name: set_priority()
563 // desc: set thread priority for self
564 //-----------------------------------------------------------------------------
565 t_CKBOOL XThreadUtil::set_priority( t_CKINT priority )
566 {
567 // pass it along with self thread
568 set_priority( pthread_self(), priority );
569 return TRUE;
570 }
571 t_CKINT XThreadUtil::get_max_priority()
572 {
573 return sched_get_priority_max( SCHED_RR );
574 }
575 t_CKINT XThreadUtil::get_min_priority()
576 {
577 return sched_get_priority_min( SCHED_RR );
578 }
579 #else
580 //-----------------------------------------------------------------------------
581 // name: set_priority()
582 // desc: set thread priority
583 //-----------------------------------------------------------------------------
584 t_CKBOOL XThreadUtil::set_priority( CHUCK_THREAD tid, t_CKINT priority )
585 {
586 // if priority is 0 then done
587 if( !priority ) return TRUE;
588
589 // log
590 EM_log( CK_LOG_FINE, "setting thread [0x%x] priority to: %ld...", (t_CKUINT)GetThreadId(tid), priority );
591
592 // set the priority the thread, windows style
593 if( !SetThreadPriority( tid, priority ) )
594 return FALSE;
595
596 return TRUE;
597 }
598 //-----------------------------------------------------------------------------
599 // name: set_priority()
600 // desc: set thread priority for self
601 //-----------------------------------------------------------------------------
602 t_CKBOOL XThreadUtil::set_priority( t_CKINT priority )
603 {
604 // pass it along with self thread
605 set_priority( GetCurrentThread(), priority );
606 return TRUE;
607 }
608 t_CKINT XThreadUtil::get_max_priority()
609 {
610 return THREAD_PRIORITY_HIGHEST; // THREAD_PRIORITY_TIME_CRITICAL;
611 }
612 t_CKINT XThreadUtil::get_min_priority()
613 {
614 return THREAD_PRIORITY_LOWEST;
615 }
616 #endif
617