gpt4 book ai didi

c - Pthread_join() 卡在线程数组上

转载 作者:行者123 更新时间:2023-11-30 19:50:39 28 4
gpt4 key购买 nike

我一直在使用 pthreads,我使用 for 循环和 ProducerThread[index] 和 conssumerThread[index] 将它们创建到一个数组中,从 0 到用户想要的任意数量(例如每个 3 个线程)。

线程正常工作并在需要时插入/删除项目。它们处于无限 while 循环中,在 main 从用户指定的 sleep 中唤醒后,使用全局变量标志 (endFlag) 进行中断。

我的问题是,我似乎无法关闭线程,基本上 pthread_join(thread[index], NULL) 实际上并没有通过我的任何一个线程数组,它只是挂起。

下面是关闭线程函数,如上所述,线程确实工作并按照我的预期进行输出,但它们只是没有按照我预期的那样关闭。

我尝试将 pthread_join() 移动到 main (当前在一个函数中),向后移动数组索引 - 与索引++,移动两个线程数组的顺序(先是 2,然后是 1),然后休眠 main再次希望能够成功,这样所有线程都有机会结束。所有这些都没有成功,而且我在网上看到的许多问题与我遇到的并不完全相同。

/*
CloseThread function takes the pointer to the start of the array for the producer and consumer, the total threads (producer and consumer) entered by user
*/
void closeThreads( pthread_t *producerThread, pthread_t *consumerThread, int producerThreadCount, int consumerThreadCount )
{
//flag to verify the thread closure
int closed = -1;
// for loop to close threads at consumerThread @ index value
for ( int index = 0; index < consumerThreadCount; index++ )
{
// pthread_join returns 0 if successful, closing the thread @ index
closed = pthread_join ( consumerThread[ index ], NULL );
// thread failed to close if closed doesnt equal 0.
if ( closed != 0 )
{
fprintf ( stderr, "Thread failed to create." );
exit ( 4 );
}//end of the failed to close issue.
}// end of consumer thread close procedure
// for loop to close the producer threads
for ( int index = 0; index < producerThreadCount; index++ )
{
// closes a thread in the array producerThread @ index value
pthread_join ( producerThread[ index ], NULL );
// unsuccessful
if ( closed != 0 )
{
fprintf ( stderr, "Thread failed to close." );
exit ( 3 );
}
}// end of join producer threads
}// end of close threads

我应该让两个线程数组将每个线程与主线程连接起来,但这并没有发生,控制台就像仍在计算一样挂起。

编辑:抱歉,我将索引测试修复为索引++,就像现在实际情况一样,无论哪种方式都会产生相同的挂起问题。

最佳答案

您的循环例如:

for ( int index = 2; index < consumerThreadCount; index-- )

应该是:

for ( int index = 0; index < consumerThreadCount; ++index )

关于c - Pthread_join() 卡在线程数组上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58715242/

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