我在Windows應用程序中使用pthreads。我注意到我的程序處於死鎖狀態 - 一個快速檢查顯示發生了以下情況:pthreads和CreateThread的死鎖
線程1產生線程2.線程2產生線程3.線程2在線程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 [email protected]()
#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 ??
您在創建線程時是否使用了任何屬性? – 2009-02-19 21:39:27
不,完全沒有屬性(爲屬性傳遞NULL指針)。 – 2009-02-19 21:41:41