2014-01-06 43 views
0

我对我写了一个小程序运行一些测试。它运行另一个程序,它根据我给它的输入执行一些文件操作。这一计划的全部目的就是要打破工作的一个大包成小包,以提高性能(发送10小包10个版本的程序,而不是等待一个更大的一个来执行,简单的分而治之的)。不确定为什么会产生这么多线程

问题在于这样一个事实,虽然我相信我已经限制了将要创建的线程数,我已经设置了测试消息表明有许多不是应该有运行多个线程。我很确定我在这里做错了什么。

代码片断:

if (finish != start){ 
    if (sizeOfBlock != 0){ 
      num_threads = (finish - start)/sizeOfBlock + 1; 
     } 
    else{ 
     num_threads = (finish-start) + 1; 
    } 
    if (num_threads > 10){ // this should limit threads to 10 at most 
     num_threads == 10; 
    } 
    else if (finish == start){ 
     num_threads = 1; 
    } 
} 



    threads = (pthread_t *) malloc(num_threads * sizeof(pthread_t)); 

    for (i = 0; i < num_threads; i++){ 
     printf("Creating thread %d\n", i); 
     s = pthread_create(&threads[i], NULL, thread, &MaxNum); 
     if (s != 0) 
      printf("error in pthread_create\n"); 
     if (s==0) 
      activethreads++; 
    } 
    while (activethreads > 0){ 
     //printf("active threads: %d\n", activethreads); 
    } 
    pthread_exit(0); 
+0

好吧,也许你应该打印出来NUM_THREADS的价值,不是吗? – OldProgrammer

+0

你malloc的线程数,但我没有看到一个免费的()。 – hetepeperfan

回答

2

此代码是无用:

if (num_threads > 10){ // this should limit threads to 10 at most 
    num_threads == 10 
} 

num_threads == 10比较num_threads10然后抛出程。你想分配,而不是:

if (num_threads > 10){ // this should limit threads to 10 at most 
    num_threads = 10; 
} 

此外,还有许多;缺少你的代码,在未来,请尽量提供一个自包含的例子,编译代码。

+0

我们对此深感抱歉,我加了括号使if语句更清楚(他们以前只是单一的线)。谢谢你指出等值与赋值符号,我一定忽略了那十次。 –

+0

@MarshallTigerus没问题,它发生在最好的;) –

相关问题