I want to create a number of threads specified by the user. The code I have written for this is:
int nhijos = atoi(argv[1]);
thread = malloc(sizeof(pthread_t)*nhijos);
for (i = 0; i < nhijos; i++){
if (pthread_create ( &thread[i], NULL, &hilos_hijos, (void*) &info ) != 0){
perror("Error al crear el hilo. \n");
exit(EXIT_FAILURE);
}
Is this correct?
Yes, but I would do the following:
validate that argc > 1 before calling atoi(argv[1])
validate numberOfThreads is a positive number and less than a reasonable range. (In case the user types 1000000).
validate the return value from malloc is not null.
pthread_create will not set errno on failure. So perror may not be the right function to call on failure.
...
if (argc > 1)
{
int numberOfThreads = atoi(argv[1]);
if ((numberOfThreads <= 0) || (numberOfThreads > REASONABLE_THREAD_MAX))
{
printf("invalid argument for thread count\n");
exit(EXIT_FAILURE);
}
thread = malloc(sizeof(pthread_t)*numberOfThreads);
if (thread == NULL)
{
printf("out of memory\n");
exit(EXIT_FAILURE);
}
for (i = 0; i < numberOfThreads; i++)
{
if (pthread_create ( &thread[i], NULL, &hilos_hijos, (void*) &info ) != 0)
{
printf("Error al crear el hilo. \n");
exit(EXIT_FAILURE);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With