如何让一个线程停止另一个线程?

How do I make a thread stop another thread?

我基本上刚刚发现多线程编程的存在,并且我盲目地玩弄这个概念很开心。

我正在尝试做的是一个每秒动态检查的计时器,同时用户继续以某种形式与程序交互。

这是我到目前为止能够完成的:

void* timer (void* threadToStop)
{
    pthread_t* threadName = threadToStop;

    time_t startTime = time(NULL);
    time_t currentTime;
    int elapsedTime;
    int remainingTime;

    do {

        if (currentTime != time(NULL)) 
        {
            currentTime = time(NULL);
            elapsedTime = currentTime - startTime;
            remainingTime = 10 - elapsedTime;
            printf("%d ", remainingTime);
            fflush(stdout);
        }

    } while (remainingTime > 0);

    pthread_cancel(*threadName);

    return NULL;
}

void* func (void* vargp)
{
    getchar();

    return NULL;
}

int main(void)
{

    pthread_t funcId;
    pthread_create(&funcId, NULL, func, NULL);

    pthread_t timerId;
    pthread_create(&timerId, NULL, timer, &funcId);

    pthread_join(funcId, NULL); 

    return EXIT_SUCCESS;
}

两个线程从两个不同的函数创建并同时启动 运行。

"func" 只是一个要求用户输入字符的虚拟函数。这只是让用户在后台计时器 运行 时与程序交互的一种方式。

"timer" 是不言自明的:它是每秒启动和更新计时器的函数。创建此线程时,它还会获取 func 的线程 ID 作为参数。时间到了,我调用 pthread_cancel 函数以使用其 id 停止 func 的线程。

这个程序的大部分工作:当我能够在控制台中输入字符时,计时器保持 运行,当我按下回车键时,pthread_join 功能启动并且主要功能到达终点。但是,当计时器用完时,func 线程不会被取消,我很难弄清楚原因。

代码在使用前未初始化 currentTime

  time_t currentTime;
  int elapsedTime;
  int remainingTime;

  do {

    if (currentTime != time(NULL)) 

一个线程只有在通过或"sitting on"一个所谓的取消点.

时才会被取消

getchar()不一定是取消点

POSIX 个线程的强制和可选取消点列表是 here


为了阐明真正发生的事情替换:

  pthread_cancel(...);

作者:

  errno = pthread_cancel(...);
  if (0 != errno)
  {
    perror("pthread_cancel() failed");
  }