キー入力があるまでタスクをwhile(1)みたいに行う方法
stdinかなんかをnonblockingでやるのではなく、別threadでタスクを実行しておいて、master threadでそいつを適当なタイミングで止めてやるという話。
参考: pthreadのキャンセル
pthread_cancelというのがあり、cancel pointをワーカスレッド側に用意( pthread_testcancel)してやればよい。ただ、このサンプルだとsleepがcancel pointになるので問題なかったりもする。
//! gcc -o hoge.bin hoge.c -lpthread #include <stdio.h> #include <pthread.h> #include <time.h> #include <pthread.h> typedef struct _thread_arg { int test; } thread_arg_t; void thread_func( void *tmp ) { thread_arg_t *arg = ( thread_arg_t * ) tmp; time_t t; while ( 1 ) { time( &t ); printf( "%2d: %s", arg->test, ctime( &t ) ); fflush( stdout ); sleep( 1 ); pthread_testcancel( ); } } int main( void ) { pthread_t thread; thread_arg_t targ = { .test = 1 }; pthread_create( &thread, NULL, ( void * ) thread_func, ( void * ) &targ ); getchar(); pthread_cancel( thread ); pthread_join( thread, NULL ); printf( "finished\n" ); return 0; }