gpt4 book ai didi

windows - pthreads 和 CreateThread 的死锁

转载 作者:可可西里 更新时间:2023-11-01 14:33:00 25 4
gpt4 key购买 nike

我在 Windows 应用程序中使用 pthreads。我注意到我的程序陷入了僵局——快速检查表明发生了以下情况:

线程 1 生成了线程 2。线程 2 生成了线程 3。线程 2 等待来自线程 3 的互斥量,而线程 3 没有解锁。

所以,我去 gdb 中调试,在回溯第三个线程时得到以下信息:

Thread 3 (thread 3456.0x880):
#0 0x7c8106e9 in KERNEL32!CreateThread ()
from /cygdrive/c/WINDOWS/system32/kernel32.dll
Cannot access memory at address 0x131

不知何故,它在 Windows CreateThread 函数中卡住了,死锁了!显然,当它甚至无法开始执行代码时,它就无法解锁互斥量。然而,尽管它显然卡在这里,但 pthread_create 返回零(成功)。

特别奇怪的是,Linux 上的同一个应用程序没有这样的问题。世界上有什么会导致线程在创建过程中挂起(!?)但成功返回,就好像它已正确创建一样?

编辑:响应代码请求,这里有一些代码(简化):

线程的创建:

if ( pthread_create( &h->lookahead->thread_handle, NULL, (void *)lookahead_thread, (void *)h->thread[h->param.i_threads] ) )
{
log( LOG_ERROR, "failed to create lookahead thread\n");
return ERROR;
}
while ( !h_lookahead->b_thread_active )
usleep(100);
return SUCCESS;

请注意,它一直等到 b_thread_active 被设置,所以 b_thread_active 以某种方式被设置,所以被调用的线程必须做一些事情......

...这是 lookahead_thread 函数:

void lookahead_thread( mainstruct *h )
{
h->lookahead->b_thread_active = 1;
while( !h->lookahead->b_exit_thread && h->lookahead->b_thread_active )
{
if ( synch_frame_list_get_size( &h->lookahead->next ) > delay )
_lookahead_slicetype_decide (h);
else
usleep(100); // Arbitrary number to keep thread from spinning
}
while ( synch_frame_list_get_size( &h->lookahead->next ) )
_lookahead_slicetype_decide (h);
h->lookahead->b_thread_active = 0;
}

lookahead_slicetype_decide (h);是线程所做的事情。

互斥量,synch_frame_list_get_size:

int   synch_frame_list_get_size( synch_frame_list_t *slist )
{
int fno = 0;

pthread_mutex_lock( &slist->mutex );
while (slist->list[fno]) fno++;
pthread_mutex_unlock( &slist->mutex );
return fno;
}

线程2的回溯:

Thread 2 (thread 332.0xf18):
#0 0x00478853 in pthread_mutex_lock ()
#1 0x004362e8 in synch_frame_list_get_size (slist=0x3ef3a8)
at common/frame.c:1078
#2 0x004399e0 in lookahead_thread (h=0xd33150)
at encoder/lookahead.c:288
#3 0x0047c5ed in ptw32_threadStart@4 ()
#4 0x77c3a3b0 in msvcrt!_endthreadex ()
from /cygdrive/c/WINDOWS/system32/msvcrt.dll
#5 0x7c80b713 in KERNEL32!GetModuleFileNameA ()
from /cygdrive/c/WINDOWS/system32/kernel32.dll
#6 0x00000000 in ??

最佳答案

我会尝试仔细检查线程 2 和线程 3 中的互斥量。Pthreads 是使用标准 Windows API 为 Windows 实现的;所以windows和linux版本之间会有细微的差别。这是一个奇怪的问题,但话又说回来,这在线程中经常发生。

您能否尝试发布一段在线程 2 和线程 3 应该启动的函数中完成锁定的代码?

根据代码进行编辑

你有没有解锁线程 2 中的互斥量?您的跟踪显示它锁定了一个互斥锁,然后创建了一个线程来完成所有试图锁定互斥锁的工作。我猜在线程 2 返回 SUCESS 之后它会成功吗?另外,你为什么要使用标志和休眠,也许障碍或条件变量用于进程同步可能更健壮。

另一个注意事项,b_thread_active 标志是否标记为 volatile ?也许编译器正在缓存一些东西以防止它爆发?

关于windows - pthreads 和 CreateThread 的死锁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/567278/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com