Pthread_join()挂在线程数组上

问题描述 投票:0回答:1

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

线程正常工作,并在需要时插入/删除项目。它们是无限的while循环,在主循环从用户指定的睡眠中唤醒后,使用全局变量标志(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连接起来,但是那没有发生,控制台就像它仍在计算那样挂起。

编辑:对不起,我将索引的测试固定到了索引++,就像现在这样,无论哪种方式都给出了相同的问题。

c arrays multithreading synchronization
1个回答
0
投票

您的循环,例如:

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

应该是:

for ( int index = 0; index < consumerThreadCount; ++index )
© www.soinside.com 2019 - 2024. All rights reserved.