c - Pthread_join() 挂在线程数组上
问题描述
我一直在使用 pthreads,我使用 for 循环和 producerThread[index] 和 conssumerThread[index] 将它们创建到一个数组中,从 0 到用户想要的任意数量(例如每个 3 个线程)。
线程正常工作并在需要时插入/移除项目。它们处于无限 while 循环中,在 main 从用户指定的睡眠中唤醒后,使用全局变量标志 (endFlag) 中断。
我的问题是我似乎无法关闭线程,基本上 pthread_join(thread[index], NULL) 实际上并没有通过我的任何一个线程数组,它只是挂起。
下面是关闭线程函数,如上所述,线程确实可以正常工作并且按照我的预期进行输出,但是它们并没有像我期望的那样关闭。
我尝试将 pthread_join() 移动到 main 中(当前在一个函数中),通过数组向后移动索引 - 与 index++ 相比,移动两个线程数组的顺序(先是 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
我应该让两个线程数组将每个线程与 main 连接起来,但这并没有发生,控制台就像它仍在计算一样挂起。
编辑:对不起,我修复了我对 index 的测试——就像现在实际上一样,将 index++ 修改为 index++,无论哪种方式都给出了相同的挂起问题。
解决方案
您的循环,例如:
for ( int index = 2; index < consumerThreadCount; index-- )
应该是:
for ( int index = 0; index < consumerThreadCount; ++index )
推荐阅读
- python - Array 像 List 一样打印,但它是变量资源管理器中的单个整数?为什么?
- r - R caret createFolds 与 createMultiFolds 的差异
- django - 生产中的神秘 Django API 行为
- mysql - Many2Many JoinTable 中的自定义字段
- javascript - MongooseJS - 插入子文档而不验证文档
- mysql - 如何让 max(table1.date1) 小于 min(table1.date2)
- flutter - Flutter,重定向外部应用程序后打开通用链接
- python - PyTorch:“CrossEntropyLoss”对象没有属性“项目”
- vba - Visual Basic 中的 Application.OnTime
- jquery - 如何使用 AWS API Gateway 启用 CORS