2016年5月3日 星期二

About pthread_timedjoin_np Function


範例程式隨便寫的, 別太認真.

關於 pthread_timedjoin_np() 的回傳值
當 Thread 還在執行時, 回傳 nStstus = 110
#define ETIMEDOUT   110 /* Connection timed out */
當 Thread 還在結束時, 回傳 nStstus = 0x00
但只能問到一次是 0x00
再問一次, 就會變成 22
#define EINVAL      22  /* Invalid argument */
這一點會讓寫程式時, 就得立刻記錄 Thread已結束,
不然別的 Thread 就問不到已結束.
pthread_exit((void *)3) 的0x03 是收不到的.

//-----------------------------------------------------------------------------
#include 
//-----------------------------------------------------------------------------
void *thread_start( void *para)
{
 int i = 0;
 printf("pthread (%u) begin (%d).\n", clock(), i);
 for( i= 1; i< 10; i++)
 {
     printf("pthread (%u) - (%d).\n", clock(), i);
     sleep(2); // 2sec
 }
 printf("pthread (%u) pthread_exit()-1.\n", clock());
 pthread_exit((void *)3);
 printf("pthread (%u) pthread_exit()-2.\n", clock());
 sleep(5);
 printf("pthread (%u) return.\n", clock());
 return (void *)2;
}
//-----------------------------------------------------------------------------
int main_ThreadTest()
{
 pthread_t id;
 int i,ret;
 int nStstus;
 struct timespec sWaitTime;
 void *pThreadRet = NULL;

 ret = pthread_create( &id, NULL, thread_start, NULL);
 clock_gettime( CLOCK_REALTIME, &sWaitTime);
 sWaitTime.tv_sec += 1; // wait 1sec
 nStstus = pthread_timedjoin_np( id, &pThreadRet, &sWaitTime);
 nprintf( "pthread_timedjoin_np-2 (%u) Status:%d, pThreadRetSc:%d\n", clock(), nStstus, ret);
 if(ret!=0)
 {
     printf ("Create pthread error!\n");
     exit (1);
 }
 for(i=0 ; i < 1000; i++)
 {
  clock_gettime( CLOCK_REALTIME, &sWaitTime);
  sWaitTime.tv_sec += 1; // wait 1sec
  nStstus = pthread_timedjoin_np( id, &pThreadRet, &sWaitTime);
  nprintf( "pthread_timedjoin_np-2 (%u)Status:%d, pThreadRetSc:%d\n", clock(), nStstus, ret);
  usleep(100);
 }
// #define EBUSY       16  /* Device or resource busy */
// #define EINVAL      22  /* Invalid argument */
// #define ETIMEDOUT   110 /* Connection timed out */
// #define ECONNREFUSED    111 /* Connection refused */
// pthread_join(id,NULL);//等待線程(pthread)結束
 return (0);
}


沒有留言:

張貼留言