c - 当线程在外部终止时 NetServerEnum block

标签 c multithreading winapi netapi32

(在 Win32 api 中工作,在 C 环境中使用 VS2010)

我有一个双线程应用程序。第一个线程 fork 第二个并等待给定的时间间隔 - 'TIMEOUT',然后对其调用 TerminateThread()。 同时,第二个线程调用 NetServerEnum()

似乎当达到超时时,无论 NetServerEnum 是否成功返回,第一个线程都会死锁。 我已经注意到 NetServerEnum 创建了它自己的工作线程。

我最终以死锁中的一个线程告终,通常是在 ntdll.dll!RtlInitializeExceptionChain 上,无法正常退出我的进程。

最佳答案

因为评论太长了:

逐字记录来自 MSDN ,请允许我使用 te answer form(我强调):

TerminateThread is a dangerous function that should only be used in the most extreme cases. You should call TerminateThread only if you know exactly what the target thread is doing, and you control all of the code that the target thread could possibly be running at the time of the termination. For example, TerminateThread can result in the following problems:

  • If the target thread owns a critical section, the critical section will not be released.
  • If the target thread is allocating memory from the heap, the heap lock will not be released. *If the target thread is executing certain kernel32 calls when it is terminated, the kernel32 state for the thread's process could be inconsistent.
  • If the target thread is manipulating the global state of a shared DLL, the state of the DLL could be destroyed, affecting other users of the DLL.

通过阅读本文,很容易理解为什么取消(终止)卡在系统调用中的线程是个坏主意。


OP 设计的一种可能的替代方法可能是产生一个调用 NetServerEnum() 的线程,并让它运行直到系统调用返回。

同时,主线程可以做其他事情,例如通知用户扫描网络所需的时间比预期的要长。

关于c - 当线程在外部终止时 NetServerEnum block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16950182/

相关文章:

c# - 正确使用 .NET MemoryCache 的锁定模式

c++ - 当计算机处于 sleep 状态时电源状态发生变化时,我可以收到通知吗?

winapi - windows上的fadvise/madvise等价物是什么?

c++ - 为什么这个程序是用 gcc 编译的,而不是用 g++ 编译的?

c - 编译器(通过链接时优化)如何处理快速返回的函数(提前退出路径)?

c - 如何使用 sscanf 将一行读入 5 个变量

c - 为什么这个程序会导致无限循环输出?

javascript - nodejs 是否支持多线程?

具有已知池大小但未知工作人员的 Java- FixedThreadPool

c - 多个原始输入缓冲区