簡體   English   中英

在C中經過一定時間后終止主線程

[英]Terminating main thread after a certain time in C

我使用POSIX線程創建了兩個線程數組。有兩個線程函數Student和Teacher(我在這里沒有顯示它們)。 我的示例程序如下。 我想設定一個時間限制(例如10秒),在此時間之后,無論相應線程是否完成,主線程都會自動退出。 我該怎么做?

示例代碼片段:

int main(void)
{
    pthread_t thread1[25];
    pthread_t thread2[6];
    int i;
    int id1[25];   //for students
    int id2[6];   //for teachers

    for(i=0;i<25;i++)
    {
          id1[i]=i;
          id2[i]=i;
          pthread_create(&thread1[i],NULL,student,(void*)&id1[i] );

          if(i<6)
          {
             pthread_create(&thread2[i],NULL,teacher,(void*)&id2[i]);
          }
   }



  for (i=0;i<25;i++)
  {
    pthread_join(thread1[i],NULL);  
     if(i<6)
          {
             pthread_join(thread2[i],NULL);
          }
  }

 return 0;

}

在一定時間后,我還必須在上述代碼中添加哪些其他內容來終止主線程? (例如:10秒)

您需要的是pthread定時連接。 請參見下面的代碼段

struct timespec
{
    time_t tv_sec;     /* sec */
    long   tv_nsec;    /* nsec */
};

struct timespec ts;

if (clock_gettime(CLOCK_REALTIME, &ts) == -1)
{
    printf("ERROR\n");
}


ts.tv_sec += 10; //10 seconds

int st = pthread_timedjoin_np(thread, NULL, &ts); //only wait for 10 seconds
if (st != 0)
{
    printf("ERROR\n");
}

有關其他信息,請參考手冊頁http://man7.org/linux/man-pages/man3/pthread_tryjoin_np.3.html

如果只希望在等待10秒鍾后終止整個過程,則只需使用適當的睡眠函數用pthread_join調用替換整個for -loop即可。 您可以使用nanosleepclock_nanosleepthrd_sleep或僅

sleep(10);

之后,您的main功能將超出范圍並終止該過程。

當心,所有這些功能對到達中間的信號都很敏感。

一種方法是創建另一個將休眠10秒鍾的線程,然后調用exit() (這將終止整個過程):

void *watchdog(void *arg)
{
    sigset_t all_sigs;

    /* Block all signals in this thread, so that we do not have to
     * worry about the sleep() being interrupted. */ 
    sigfillset(&all_sigs);
    sigprocmask(SIG_BLOCK, &all_sigs, NULL);
    sleep(10);
    exit(0);
    return NULL; /* not reached */
}

在創建其他線程之后,從主線程創建此線程,並將其分離:

pthread_create(&watchdog_thread, NULL, watchdog, NULL);
pthread_detach(watchdog_thread);

現在,您的過程將在主線程加入其他線程之后完成時或在看門狗線程調用exit() (以先發生者為准exit()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM