首页 > 解决方案 > 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++,无论哪种方式都给出了相同的挂起问题。

标签: carraysmultithreadingsynchronization

解决方案


您的循环,例如:

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

应该是:

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

推荐阅读