【问题标题】:Create a dynamic number of threads创建动态线程数
【发布时间】:2012-06-25 00:31:39
【问题描述】:

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

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

这是正确的吗?

【问题讨论】:

  • 为什么?为什么要创建用户定义的多个线程?只需获取完成工作所需的线程数即可。
  • 因为用户应该指定并发线程的数量...因为这就是我们应该如何编程这个项目...

标签: c multithreading pthreads


【解决方案1】:
#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,那你为什么不释放它呢?

【讨论】:

  • 编译时抛出错误...我之前尝试过,但它会抛出警告,这就是我使用 malloc 的原因
  • padre.c:12:5:警告:ISO C90 禁止可变长度数组“thread_id”padre.c:70:2:警告:从不兼容的指针类型 /usr 传递“pthread_create”的参数 1 /include/pthread.h:225:12:注意:预期为“pthread_t * restrict”,但参数的类型为“pthread_t **”padre.c:80:2:警告:传递参数 1来自不兼容指针类型 /usr/include/pthread.h:225:12 的“pthread_create”:注意:预期为“pthread_t * restrict”,但参数类型为“pthread_t **”padre.c:89 :7: 警告:传递 'pthread_join' 的参数 1 从指针中生成整数而无需强制转换
  • 哦,在 c90 中我认为 VLA 在 c99 中是不允许的,这些是允许的。这就是为什么你会收到警告stackoverflow.com/questions/3082126/…
  • 我明白了。那么在那种情况下那是有效的。我试试看。
【解决方案2】:

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

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

【讨论】:

  • 忘记检查 malloc。以及检查 argc 的不错补充。谢谢
猜你喜欢
  • 2012-04-22
  • 1970-01-01
  • 1970-01-01
  • 2012-06-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-11
  • 2020-04-01
相关资源
最近更新 更多