如何使用用户指定的动态no线程为此函数执行多线程
答案 0 :(得分:0)
以下提议的代码:
malloc()
和scanf()
fork()
现在建议的代码:
#include <stdio.h> // printf(), scanf(), perror()
#include <stdlib.h> // exit(), EXIT_FAILURE
#include <unistd.h> // fork(), execvp()
#include <sys/types.h>
#include <sys/wait.h> // waitpid()
// prototypes
void mandelseries(int);
#define MAX_STR_LEN 15
#define ARRAY_SIZE 16
void mandelseries(int numImages)
{
pid_t child[ numImages ];
for( int i = 0; i < numImages; i++ )
{
child[i] = fork();
switch( child[i] )
{
case -1:
perror( "fork failed" );;
break;
case 0: // child
{
char **argarry = malloc( ARRAY_SIZE * sizeof( char* ) );
if( !argarry )
{
perror( "malloc for arg array failed" );
exit( EXIT_FAILURE );
}
// implied else, malloc successful
// ... fill in arguments here
execvp( argarry[0], argarry);
perror( "execvp failed" );
exit( EXIT_FAILURE );
}
break;
default: // parent
break;
} // end switch()
}
for( int i=0; i < numImages; i++ )
{
int status;
if( -1 != child[i] )
{
waitpid(child[i], &status, 0);
}
}
}
int main( void )
{
int numImages;
printf("Enter number of times:");
if( 1 != scanf("%d", &numImages) )
{
perror( "scanf failed" );
exit( EXIT_FAILURE );
}
// implied else, scanf successful
mandelseries(numImages);
exit(0);
}