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

标签 c multithreading pthreads

我基本上刚刚发现多线程编程的存在,并且我很享受盲目地尝试这个概念。

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

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

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”只是一个虚拟函数,要求用户输入一个字符。这只是计时器在后台运行时让用户与程序交互的一种方式。

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

该程序大部分情况下都有效:当我能够在控制台中输入字符时,计时器保持运行,当我按下 Enter 键时,pthread_join 函数将启动并执行 main 函数到达终点。但是,当计时器耗尽时,func 线程不会被取消,我很难找出原因。

最佳答案

代码在使用currentTime之前错过了初始化:

  time_t currentTime;
  int elapsedTime;
  int remainingTime;

  do {

    if (currentTime != time(NULL)) 
<小时/>

只有当线程通过或“坐在”所谓的取消点时才会被取消。

getchar() 不一定是取消点。

POSIX 线程的强制和可选取消点列表为 here .

<小时/>

要了解真正发生的情况,请替换:

  pthread_cancel(...);

作者:

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

关于c - 如何让一个线程停止另一个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101722/

相关文章:

c++ - 为什么在删除原子引用计数智能指针中的数据之前需要获取屏障?

c++ - C++中的线程序列化是什么意思?

c - 如何为 pthread 堆栈正确分配内存

java - 在不使用任何预定义函数的情况下从字母数字字符串中提取数值

c - 如何使用函数扫描二维数组而不删除其内容

c++ - 什么时候全局变量实际上被认为是好的/推荐的做法?

c - 如何在c中使用互斥锁与多线程同步进程

python - 运行时错误: Task got Future <Future pending> attached to a different loop

c - 这是一个过于复杂的 pthreads 代码吗?

c - 从 int、float、char、double 进行类型转换