Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014 #include <iostream>
00015
00016 #include "Thread.h"
00017 #include <sstream>
00018 #include "ros/ros.h"
00019
00020 using namespace std;
00021
00031 void threadWrapper ( Thread* instance )
00032 {
00033
00034 instance->run();
00035
00036 }
00037
00038 void Thread::start(const char* name)
00039 {
00040
00041 int ret = pthread_create ( &m_Thread, NULL, reinterpret_cast<void* ( * ) ( void* ) > ( threadWrapper ), this );
00042 if ( ret != 0 )
00043 {
00044 ostringstream stream;
00045 stream << "pthread_create returned error " << ret;
00046 ROS_ERROR_STREAM( stream.str() );
00047 }
00048 else
00049 {
00050 if (!name) {
00051 name="UnnamedThread";
00052 }
00053 std::ostringstream s;
00054 s << "Created new Thread: \"" << name << "\" " << (int)m_Thread << " " << std::hex << m_Thread << std::dec;
00055 ROS_INFO_STREAM( s.str() );
00056 }
00057
00058 }
00059
00060 void Thread::cancel()
00061 {
00062 const int max_retry = 5;
00063 int retry = 0;
00064 int ret;
00065
00066 do
00067 {
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
00078
00079
00080
00081 ret = pthread_cancel ( m_Thread );
00082 if ( ret != 0 )
00083 {
00084 ostringstream stream;
00085 stream << "pthread_cancel returned error " << ret;
00086 ROS_ERROR_STREAM( stream.str() );
00087 }
00088 retry++;
00089 usleep ( 1000000 );
00090 }
00091 while ( ( ret != 0 ) && ( retry < max_retry ) );
00092
00093 if (ret!=0) {
00094 ROS_ERROR( "Canceling thread failed." );
00095 } else {
00096 ROS_DEBUG_STREAM( "Thread " << m_Thread << " cancelled." );
00097 }
00098
00099
00100 }
00101
00102 void Thread::join()
00103 {
00104 ROS_INFO_STREAM( "Joining Thread..." );
00105 int ret = pthread_join ( m_Thread, NULL );
00106 if ( ret != 0 )
00107 {
00108 ostringstream stream;
00109 stream << "pthread_join returned error " << ret;
00110 ROS_ERROR_STREAM( stream.str() );
00111 }
00112 }
00113
00114 void Thread::setCancelSettings()
00115 {
00116
00117 pthread_setcancelstate ( PTHREAD_CANCEL_ENABLE, NULL );
00118 pthread_setcanceltype ( PTHREAD_CANCEL_DEFERRED, NULL );
00119 }
00120
00121 void Thread::testCancel()
00122 {
00123 pthread_testcancel();
00124 }
00125
00126 #ifdef __TEST__
00127
00128 #include <iostream>
00129
00130 int main ( int argc, char **argv )
00131 {
00132 std::cout << "UNITTEST" << std::endl;
00133 return 0;
00134 }
00135 #endif