创建动态数量的线程

时间:2012-06-22 16:56:17

标签: 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);
}   

这是对的吗?

2 个答案:

答案 0 :(得分:6)

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

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

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

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

  4. pthread_create不会在失败时设置errno。所以perror可能不适合召唤失败。

  5. ...

    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); 
            }    
        }
    

答案 1 :(得分:3)

#include<stdio.h>
#include<pthread.h>

void* thread_function(void)
{
    printf("hello");
}
int main(int argc,char *argv[])
{
    int noOfThread= atoi(argv[1]);
    pthread_t thread_id[noOfThread];
    int i;
    int status;
    for(i=0;i<noOfThread;i++)
    {
        pthread_create (&thread_id[i], NULL , &thread_function, NULL);
    }  

    for(i=0;i<noOfThread;i++)
        pthread_join(thread_id[i],NULL);   
}

现在编译thi并以

运行
./a.exe 3

因此将创建3个线程


在您的代码中

1&GT;你为什么要去malloc?

2 - ;如果是malloc,那么为什么你不打算释放它呢?