C for循环中线程的奇怪行为
我们必须用C语言实现一个多线程桶排序算法。我简化了代码,它也有同样的问题C for循环中线程的奇怪行为,c,multithreading,pthreads,C,Multithreading,Pthreads,我们必须用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 )
#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 );
}
#包括
#包括
#包括
int max_线程;
void*bucket_排序(void*);
int main(int argc,char*argv[])
{
srand(时间(空));
如果(argc!=2)
{
printf(“错误的论证”);
退出(退出失败);
}
max_threads=(int)strtol(argv[1],NULL,10);
pthread_t*threads=malloc(sizeof(pthread_t)*max_threads);
对于(int i=0;i
如果我使用./a.out 10运行程序,输出应该如下所示:
0123456789
我知道输出的顺序可能会有所不同,但是[0,9]中的所有元素都应该只打印一次。
但结果却完全不同:
1234334445
76543543
这不是我所期望的结果。为什么我的程序的输出如此奇怪?我能做些什么,以获得我期望的行为
谢谢
Patrik进行以下更改:
if( pthread_create( &threads[i], NULL, bucket_sort, (void*)i ) )
...
int p = (int)param;
您的代码将指针传递到i
,同时变量发生变化,最后它超出范围,这是未定义的行为。传递i
值而不是指针