本文介绍了何时使用 pthread_cancel 而不是 pthread_kill?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么时候使用 pthread_cancel 而不是 pthread_kill?

When does one use pthread_cancel and not pthread_kill?

推荐答案

这两个我都不会用,但这只是个人喜好.

I would use neither of those two but that's just personal preference.

在两者中,pthread_cancel 是终止线程的最安全方法,因为该线程仅在使用 pthread_setcancelstate().

换句话说,它不应该在以可能导致死锁的方式持有资源的情况下消失.pthread_kill() 调用向特定线程发送信号,这是一种异步影响线程的方式,而不是取消它.

In other words, it shouldn't disappear while holding resources in a way that might cause deadlock. The pthread_kill() call sends a signal to the specific thread, and this is a way to affect a thread asynchronously for reasons other than cancelling it.

我的大多数线程都倾向于在循环中工作,并定期检查标志以查看它们是否应该退出.这主要是因为我在一个 pthread_kill() 很危险而 pthread_cancel() 不存在的世界里长大.

Most of my threads tends to be in loops doing work anyway and periodically checking flags to see if they should exit. That's mostly because I was raised in a world when pthread_kill() was dangerous and pthread_cancel() didn't exist.

我赞同每个线程应该完全控制自己的资源的理论,包括它的执行生命周期.我一直发现这是避免死锁的最好方法.为此,我简单地使用互斥体在线程之间进行通信(我很少发现需要真正的异步通信)和用于终止的标志变量.

I subscribe to the theory that each thread should totally control its own resources, including its execution lifetime. I've always found that to be the best way to avoid deadlock. To that end, I simply use mutexes for communication between threads (I've rarely found a need for true asynchronous communication) and a flag variable for termination.

这篇关于何时使用 pthread_cancel 而不是 pthread_kill?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 06:03