Pthread_join()挂在线程数组上

我一直在使用pthread,我已经使用for循环将它们创建为数组,并且producerThread [index]和consumerThread [index]的范围从0到用户想要的数目(例如3个线程)。

线程正常工作,并在需要时插入/删除项目。它们是无限的while循环,在主线程从用户指定的睡眠中唤醒后使用全局变量标志(endflag)中断。

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

下面是关闭线程函数,如上所述,这些线程确实可以正常工作并且正在按我的期望进行输出,但是它们只是没有按照我的期望而关闭。

我试过将pthread_join()移入main(当前在函数中),将数组向后移到index--与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 ++上,就像现在实际上那样,无论哪种方式都给出相同的挂起问题。

Heero42 回答:Pthread_join()挂在线程数组上

您的循环,例如:

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

应该是:

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

我的问题最终是当我退出我不使用的while循环时:

sem_post(&semaphore);

这可以正确关闭线程。

本文链接:https://www.f2er.com/3158111.html

大家都在问