我们要用C实现一个多线程的桶排序算法,我已经简化了代码,它有同样的问题。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
int max_threads;
void *bucket_sort( void * );
int main( int argc, char *argv[] )
{
srand( time( NULL ) );
if( argc != 2 )
{
printf( "Wrong arguements\n" );
exit( EXIT_FAILURE );
}
max_threads = ( int ) strtol( argv[1], NULL, 10 );
pthread_t *threads = malloc( sizeof( pthread_t ) * max_threads );
for( int i = 0; i < max_threads; )
{
if( pthread_create( &threads[i], NULL, bucket_sort, &i ) )
exit( EXIT_FAILURE );
i++;
}
for( int i = 0; i < max_threads; ++i )
pthread_join( threads[i], NULL );
}
void *bucket_sort( void *param )
{
int p = *( int * )param;
printf( "%d\n",p );
}
如果我用 ./a.out 10 运行程序,输出应该是这样的:
0 1 2 3 4 5 6 7 8 9
我知道输出的顺序可能会有所不同,但是 [0,9] 中的所有元素都应该只打印一次。 但是输出完全不同:
1234334445
7676543543
这不是我预期的输出。为什么我的程序输出如此奇怪?我该怎么做才能获得我期望的行为?
谢谢 帕特里克
最佳答案
进行以下更改:
if( pthread_create( &threads[i], NULL, bucket_sort, (void*)i ) )
...
int p = (int)param;
您的代码将指针传递给i
,同时变量发生变化,最终超出范围,这是未定义的行为。传递 i
值而不是指针。
关于c - for循环中线程的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23896284/