我想创建由用户指定的多个线程。我为此编写的代码是:
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);
}
这样对吗?
最佳答案
是的,但我会执行以下操作:
...
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);
}
}