如何“杀死”一个Pthread? [英] How "kill" a Pthread?

查看:219
本文介绍了如何“杀死”一个Pthread?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Pthreads,并且想知道什么是最好的方式来杀死这样的对象。在寻找类似问题后,我无法找到明确的答案,但请随时指出我的任何相关问题。

I am learning Pthreads, and was wondering what is the best way to kill such an object. After looking for similar questions I was not able to find a "clear" answer but please feel free to point me to any relevant questions.

我正在与一个小客户服务器应用程序,其中服务器主的线程正在侦听套接字以进行客户端连接。每次客户端连接时,服务器创建一个新线程在一个while true循环中执行无限工程。现在我想在同一个客户端在套接字上发送一个停止请求时停止这个循环。

I am working with a small client server application, where the server main's thread is listening on a socket for clients connections. Each time a client connects, the server create a new thread performing "infinite works" in a while true loop. Now I want to stop this loop when the same client send a "stop" request on the socket.

如何实现这样的行为,知道客户端通过ID在每个套接字消息中提供?使用共享变量(在主服务器线程和客户机服务器线程之间)作为while循环中的tes条件。使用PThread函数?

How would you implement such a behavior knowing that clients are identified through an ID provided within each socket messages ? Using a shared variable (between main server thread and client server threads) as a tes condition in the while loop. Using a PThread function ?

推荐答案

没有办法强制杀死单个POSIX线程;这是故意的,通过设计。相反,如果你的线程需要被其他线程停止,你应该设计运行它的代码来考虑这个。这样做的惯用方法是使用退出标志变量(由互斥锁保护)和条件变量。

There is no way to forcibly kill a single POSIX thread; this is intentional, by design. Instead, if your thread needs to be stoppable by other threads, you should design the code that runs in it to take this into account. The idiomatic way to do this is with an exit flag variable (protected by a mutex) and a condition variable.

还有 pthread_cancel ,可以用来请求一个线程退出。正确使用它需要使用 pthread_cleanup_push 设置清理处理程序和/或使用 pthread_setcancelstate 暂时取消取消。

There is also pthread_cancel, which can be used to request that a thread exit. Using it correctly requires setting up cleanup handlers with pthread_cleanup_push and/or disabling cancellation temporarily with pthread_setcancelstate.

这篇关于如何“杀死”一个Pthread?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆