How to stop a running pthread thread?

前端 未结 4 707
庸人自扰
庸人自扰 2020-12-18 05:27

How can I exit or stop a thread immediately?

How can I make it stop immediately when the user enters an answer? I want it to reset for every question.

Here\

4条回答
  •  被撕碎了的回忆
    2020-12-18 06:20

    Based on your code I can give a simple answer:

    In this case do not use threads at all.

    You do not need them. Store the start time, let the user answer, check the time again after user gives an answer.

    {
      time_t startTimeSec = time(NULL);
    
      // answering
    
      time_t endTimeSec = time(NULL);
      time_t timeTakenSec = endTime-startTime;
      if (timeTaken > 10) { 
        // do your thing
      }
    }
    

    To answer your question:

    You should use a mutex-protected or volatile variable to asynchronously communicate between threads. Set that variable from one thread and check it in another. Then reset its value and repeat. A simple snippet:

    int stopIssued = 0;
    pthread_mutex_t stopMutex;
    
    int getStopIssued(void) {
      int ret = 0;
      pthread_mutex_lock(&stopMutex);
      ret = stopIssued;
      pthread_mutex_unlock(&stopMutex);
      return ret;
    }
    
    void setStopIssued(int val) {
      pthread_mutex_lock(&stopMutex);
      stopIssued = val;
      pthread_mutex_unlock(&stopMutex);
    }
    

    Using pthread_cancel() is an option, but I would not suggest doing it. You will have to check the threads state after this call returns, since pthread_cancel() does not wait for the actual thread stop. And, which to me is even more important, I consider using it ugly.

提交回复
热议问题