创建动态数量的线程

Ale*_*ire 5 c multithreading pthreads

我想创建用户指定的一些线程.我为此编写的代码是:

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);
}   
Run Code Online (Sandbox Code Playgroud)

它是否正确?

sel*_*bie 6

是的,但我会做以下事情:

  1. 在调用atoi之前验证argc> 1(argv [1])

  2. 验证nhijos是正数且小于合理范围.(如果用户键入1000000).

  3. 验证malloc的返回值不为null.

  4. pthread_create不会在失败时设置errno.所以perror可能不是调用失败的正确功能.

...

if (argc > 1)
{
    int nhijos = atoi(argv[1]); 
    if ((nhijos <= 0) || (nhijos > REASONABLE_THREAD_MAX))
    {
        printf("invalid argument for thread count\n");
        exit(EXIT_FAILURE);
    }

    thread = malloc(sizeof(pthread_t)*nhijos); 
    if (thread == NULL)
    {
       printf("out of memory\n");
       exit(EXIT_FAILURE);
    }

    for (i = 0; i < nhijos; i++)
    { 
        if (pthread_create ( &thread[i], NULL, &hilos_hijos, (void*) &info ) != 0)
        { 
            printf("Error al crear el hilo. \n"); 
            exit(EXIT_FAILURE); 
        }    
    }
Run Code Online (Sandbox Code Playgroud)