新线程仅发出第一条指令,永远不会恢复

new Thread making only first instruction and never resumes

本文关键字:指令 一条 永远 恢复 线程 新线程      更新时间:2023-10-16

这是我的问题:

我正在创建线程

HANDLE Threads[THREAD_NUM]

启动线程

void LaunchThread (int i) {
  *some checks if the handle is not null etc*;
  DWORD threadId;
  threads[i] = CreateThread ( 
    NULL,
    0,
    (LPTHREAD_START_ROUTINE)*StaticMethodInvokingTheThreadFunc, 
    *StructPassingToThatMethod ( basically have a pointer and thread number)*,
    0,
    &threadId);
  *DebugMessage "thread created"*;
  *DebugMessage "with id = (threadId)"*;
}

静态方法调用函数

void DoSmth () {
  *DebugMessage "thread func started"*;
  ...;
  *then code with another messages all the way*;
}

等待功能简单

void WaitThread (i){
  *DebugMessage "wait for thread to finish"*;
  WaitForSingleObject (Threads[i], INFINITE);
}

在主函数中,序列:

LaunchThread (i);
WaitThread (i);

程序从不返回 WaitThread () 函数,并且 (!) 消息列表如下所示

"thread created"
"thread func started" (and nothing done after that message in DoSmth () func)
"with id = .."
"wait for thread to finish"

即使有 1 个线程也会发生这种情况...对于几个线程,我只是有

 for ( int t = 0; t < THREAD_NUM; t++)
   LaunchThread (t);

以及等待线程的相同循环

为什么会这样?我试图ResumeThread (),关闭线程的手柄并重新启动它,但没有任何帮助。

可能是函数 StaticMethodInvokingTheThreadFunc 实际上没有 LPTHREAD_START_ROUTINE 的签名,但这被函数指针强制强制转换为它的事实所掩盖。取下石膏。如果编译器开始抱怨,则调整函数的签名。

可能是

调用CreateThread在您的情况下是错误的。在99%的情况下都是错误的,你真的应该调用CRT库函数_beginthreadex。这个函数在内部调用CreateThread,但它也做一些初始化工作。将 CreateThread 替换为 _beginthreadex。

可能是在打印文本"线程函数已启动"之后,执行在 StaticMethodInvokingTheThreadFunc 中挂起。修改函数中的代码,或在最后一个函数的行上放置断点并调试项目以查看是否会命中断点。