C-将多线程程序编写为平方数 [英] C - writing a multi-threaded program to square numbers

查看:76
本文介绍了C-将多线程程序编写为平方数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个程序,该程序使用多个线程来计算1-10000之间的数字平方.我正在尝试使每个线程一次平方一个数字,最多8个线程.这意味着线程1-8将对8个数字求平方,并在完成时开始对下一个数字求平方,等等.

I'm trying to write a program that uses multiple threads to compute the squares of numbers between 1-10000. I am trying to get each thread to square one number at a time, with a maximum of 8 threads. This means that threads 1-8 will square 8 numbers, and as they finish they begin squaring the next number, etc.

我的代码编译没有错误,但是没有将任何内容打印到输出文件.我无法确切指出问题所在,因此有人可以给我一些提示或为我指明正确的方向吗?

My code compiles without error, but does not print anything to the output file. I can't exactly pinpoint the issue, so could someone give me some tips or point me in the right direction?

此外,对于那些提供代码帮助的人,我已经评论了我不希望对其进行更改的部分.我仍然怀疑它们是否仍然需要,但是我将它们用于该项目的其他部分,并希望保持它们不变. 谢谢.这是我的代码:

Also, for those who provide code to help, I have commented sections that I would rather not be altered. I doubt they would need to anyway, but I am using them for other parts of this project and would like to keep them the same. Thanks. Here is my code:

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

#define NUMBER_OF_THREADS 8
#define START_NUMBER 1
#define END_NUMBER 10000

FILE *f;

void *sqrtfunc(void *tid) { //function for computing squares
    int i;
    for (i = START_NUMBER; i<=END_NUMBER; i++){
        fprintf(f, "%lu squared = %lu\n", i, i*i);
    }
}

int main(){
    //Do not modify starting here
    struct timeval start_time, end_time;
    gettimeofday(&start_time, 0);
    long unsigned i;
    f = fopen("./squared_numbers.txt", "w");
    //Do not modify ending here

    pthread_t mythreads[NUMBER_OF_THREADS]; //thread variable
    long mystatus;

    for (i = 0; i < NUMBER_OF_THREADS; i++){ //loop to create 8 threads
        mystatus = pthread_create(&mythreads[i], NULL, sqrtfunc, (void *)i);
        if (mystatus != 0){ //check if pthread_create worked
            printf("pthread_create failed\n");
            exit(-1);
        }
    }
    for (i = 0; i < NUMBER_OF_THREADS; i++){
        if(pthread_join(mythreads[i], NULL)){
            printf("Thread failed\n");
        }
    }
    exit(1);

    //Do not modify starting here
    fclose(f);
    gettimeofday(&end_time, 0);
    float elapsed = (end_time.tv_sec-start_time.tv_sec) * 1000.0f + \
                    (end_time.tv_usec-start_time.tv_usec) / 1000.0f;
    printf("took %0.2f milliseconds\n", elapsed);
    //Do not modify ending here
}

我能想到的唯一解决方案是移动创建8个线程的for循环并将其放置在sqrtfunc函数的for循环内.这行得通吗?预先感谢.

The only solution I can think of is moving the for-loop that creates the 8 threads and placing it inside of the sqrtfunc function's for-loop. Would this work? Thanks in advance.

推荐答案

为避免线程争用文件访问权,每个线程都可以返回结果,该结果将由主进程放入文件中.否则线程可以准备结果字符串并锁定,然后再仅将这个字符串写入文件.下面是第一个解决方案

To avoid problem with threads fight for file access each thread can return result which will be put to file by main process. Or thread can prepare result string and lock before writing to file just this string. Below is first solution

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <pthread.h>

#define NUMBER_OF_THREADS 8
#define START_NUMBER 1
#define END_NUMBER 1000

FILE* f;

struct Thread_argument
{
    unsigned long long start;
    int range;
};

void* sqrtfunc( void* a ) //function for computing squares
{
    struct Thread_argument* argument = ( struct Thread_argument* )a;
    unsigned long long* result = calloc( argument->range, sizeof( unsigned long long ) );

    for( int i = 0; i < argument->range; i++ )
    {
        result[i] = ( argument->start + i ) * ( argument->start + i );
    }

    free( a );
    return result;
}

int main()
{
    //Do not modify starting here
    struct timeval start_time, end_time;
    gettimeofday( &start_time, 0 );
    long unsigned i;
    f = fopen( "./squared_numbers.txt", "w" );
    //Do not modify ending here
    pthread_t mythreads[NUMBER_OF_THREADS]; //thread variable
    long mystatus;
    int END = END_NUMBER + 1;
    int const range = ( END - START_NUMBER ) / ( NUMBER_OF_THREADS - 1 );

    for( int i = 0; i < NUMBER_OF_THREADS; i++ ) //loop to create 8 threads
    {
        struct Thread_argument* ta = malloc( sizeof( struct Thread_argument ) );
        ta->start = i * range + START_NUMBER;
        ta->range = range;

        if( i == NUMBER_OF_THREADS - 1 )
        {
            ta->range = ( END - START_NUMBER ) % ( NUMBER_OF_THREADS - 1 );
        }

        mystatus = pthread_create( &mythreads[i], NULL, sqrtfunc, ( void* )ta );

        if( mystatus != 0 ) //check if pthread_create worked
        {
            printf( "pthread_create failed\n" );
            exit( -1 );
        }
    }

    unsigned long long* results[NUMBER_OF_THREADS]; //thread variable

    for( int i = 0; i < NUMBER_OF_THREADS; i++ )
    {
        if( pthread_join( mythreads[i], ( void** )&results[i] ) )
        {
            printf( "Thread failed\n" );
        }
    }

    for( int i = 0; i < NUMBER_OF_THREADS - 1; i++ )
    {
        for( int j = 0; j < range; ++j )
        {
            fprintf( f, "%d %lld\n", i * range + j + START_NUMBER, results[ i ][ j ] );
        }

        free( results[ i ] );
    }

    int leftovers = ( END - START_NUMBER ) % ( NUMBER_OF_THREADS - 1 );

    for( int i = 0; i < leftovers; ++i )
    {
        fprintf( f, "%d %lld\n", ( NUMBER_OF_THREADS - 1 ) * range + i + 1, results[ NUMBER_OF_THREADS - 1 ][ i ] );
    }

    free( results[ NUMBER_OF_THREADS - 1 ] );
    fclose( f );
    //Do not modify starting here
    gettimeofday( &end_time, 0 );
    float elapsed = ( end_time.tv_sec - start_time.tv_sec ) * 1000.0f + \
                    ( end_time.tv_usec - start_time.tv_usec ) / 1000.0f;
    printf( "took %0.2f milliseconds\n", elapsed );
    //Do not modify ending here
    return 0;
}

这篇关于C-将多线程程序编写为平方数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆