多线程简单测试(输出500000000个数字)

C++代码如下:

#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<unistd.h>
//线程的最大数量
const int THREAD_MAX_NUM = 100;
pthread_t threads[THREAD_MAX_NUM];
//线程的编号
int thread_mark[THREAD_MAX_NUM];
//平均每个线程需要打印数字的个数
int avg_num;
//线程数
int pthread_num = 1;
//数字的数目
int number_num = 1;
/*
 * 输出数字的线程函数
 */
void * output_number (void * arg){
        int thread_id = *((int*)arg);
        printf("thread_id: %d\n", thread_id);
        //计算线程输出的数字的范围
        int st = 0, ed = 1;
        st = thread_id*avg_num;
        if(thread_id == pthread_num - 1){
                ed = number_num;
        }else{
                ed = st + avg_num;
        }
        char fname[32];
        sprintf(fname, "/tmp/pthread/%d.log", thread_id);
        FILE* fp = fopen(fname, "w+");
        for(int i = st; i < ed; i++){
                //printf("%d\n", i);
                fprintf(fp, "%d\n", i);
        }
        return NULL;
}
int main(int argc, char* argv[]){
        int opt;
        while((opt=getopt(argc, argv,"p:n:h"))!=-1){
                switch(opt){
                        case 'p':
                                pthread_num = atoi(optarg);
                                break;
                        case 'n':
                                number_num = atoi(optarg);
                                break;
                }
        }
        if(pthread_num < 1){
                pthread_num = 1;
        }
        if(number_num < 1){
                number_num = 1;
        }
        avg_num = number_num / pthread_num; 
        printf("pthread_num: %d\n", pthread_num);
        for(int i = 0; i < pthread_num; i++){
                thread_mark[i] = i;
                pthread_create(threads+i, NULL, output_number, thread_mark+i);
        }
        for(int i = 0; i < pthread_num; i++){
                pthread_join(threads[i], NULL);
        }
        //sleep(2);
        return 0;
}

 测试情况如下:

  1个线程(单位:秒) 6个线程(单位:秒) 12个线程(单位:秒) 15个线程(单位:秒) 16个线程(单位:秒)
均值 73.351 11.9015 9.0455 7.604 7.5105
  71.166 11.818 8.388 8.079 8.482
  74.6 12.078 16.865 6.898 8.702
  72.26 12.27 8.478 6.749 11.197
  73.475 11.954 7.087 6.895 7.547
  75.536 11.985 9.703 7.129 6.539

猜你喜欢

转载自goaheadtw.iteye.com/blog/1922750