6

我想创建用户指定的多个线程。我为此编写的代码是:

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

它是否正确?

4

2 回答 2

7

是的,但我会执行以下操作:

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

  2. validate numberOfThreads 是一个正数并且小于一个合理的范围。(如果用户键入 1000000)。

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

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

...

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); 
        }    
    }
于 2012-06-22T17:08:32.863 回答
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> 你为什么要去 malloc ?

2> 如果 malloc 那么为什么你不打算释放它呢?

于 2012-06-22T17:06:22.137 回答