【问题标题】:Perfect number calculator using pthreads使用 pthreads 的完美数字计算器
【发布时间】:2014-06-18 20:57:25
【问题描述】:

我正在尝试制作一个程序,该程序使用一种效率非常低的算法,该算法使用 POSIX 线程计算一个范围内的完美数。我似乎无法很好地掌握锁定的概念以使我的算法正常工作。我想返回一个完美数字列表。任何人都可以就如何更好地实现这一点提供一些建议吗?

具体问题: - 如何让它只打印出每个完美数字的 1 个瞬间? - 如何让它返回值而不是只打印值?

来源:

static pthread_mutex_t mtx = PTHREAD_MUTEX_INITIALIZER;

static void * threadFunc(void *arg) {

    int range, start, end;
    int i, s,  number, mod, divisor, temp, sum;

    s = pthread_mutex_lock(&mtx);   

    /* Takes in a string and pulls out the two integers */
    sscanf(arg,"%i-%i", &start, &end);
    printf("\nStart: %i\nEnd: %i\n", start, end);

    printf("\n");

    s = pthread_mutex_unlock(&mtx);

    for (number=start; number<=end; number++) { // loop through range of numbers                

        temp=0,sum=0;           
        // loops through divisors of a number and sums up whole divisors
        for (i=1; i<number; i++) {          
            //s = pthread_mutex_lock(&mtx);             
            mod = number % i;           
            //s = pthread_mutex_unlock(&mtx);           

            if (mod == 0){              
                s = pthread_mutex_lock(&mtx);               

                divisor = i; 
                sum = divisor + temp;
                temp = sum;

                s = pthread_mutex_unlock(&mtx);                     
            }                       
        }
        //if the sum of whole divisors is equal to the number, its perfect
        if (sum == number)  {           

            s = pthread_mutex_lock(&mtx);           

            printf("%i is a Perfect Number \n", sum);
            //return sum somehow;           

            s = pthread_mutex_unlock(&mtx);         
        }
    }

    return NULL;
}


int main(int argc, char *argv[]) {
    pthread_t tid[5];

    int prefect_number, i, s;

    char input[]="1-9999";

    for(i=0; i < 5; ++i) {
        pthread_create(&tid[i], NULL, &threadFunc, input);
        print_thread_info();
    }
    /* Wait for the perfect number thread to complete, then get result. */  
    for(i=0; i < 5; ++i)
        pthread_join(tid[i],NULL);

    return 0;   
}

【问题讨论】:

    标签: pthreads perfect-numbers


    【解决方案1】:

    您只需要在访问可能从另一个线程修改的数据结构(例如全局变量)或资源(例如终端)时锁定互斥锁。

    • 您无需锁定互斥锁即可访问单个线程的本地变量
    • 您无需锁定互斥锁即可读取从未被其他线程修改过的全局变量

    因此,在您的情况下,互斥锁的单一用例是防止多个 printf's() 的输出可能混淆。

    此外,让所有线程探索相同的范围是没有意义的。也许您想要 5 个线程分别探索不同的范围(0-1999、2000-2999 ... 8000-9999)?

    pthread_join() 返回线程的退出值(您传递给 return 或 pthread_exit() 的那个)。如果你想返回多个值,你可能需要创建一个全局变量来保存一个数字链表(最后需要一个互斥锁,因为不同的线程需要写入它)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-15
      • 1970-01-01
      • 2012-10-09
      • 2022-11-09
      • 1970-01-01
      • 2012-01-12
      相关资源
      最近更新 更多