#include <pthread.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
using namespace std;

#define LINE_PER_THREAD 1024

pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;

struct param{

    vector<string> vstr;
    int offset;
    int tidx;

};

//kernel function
void * std_output(void *pa){
    struct param *local = (struct param *) pa;
    vector<string> vstr = local->vstr;
    int offset = local->offset;
    int tidx = local->tidx;

    pthread_mutex_lock(&count_mutex);
    int count = 0;
    int i = offset;
    while(i < vstr.size() && i < offset + LINE_PER_THREAD){
        count++;
        i++;
    }
    cout << " thread " << tidx << " has " << count << " lines" << endl;
    pthread_mutex_unlock(&count_mutex);

}

int main(){

    ifstream input_data("input.txt");
    int line_num = 0;
    string line;
    vector<string> vstring;
    while(input_data.is_open()){
        if(!input_data.eof()){
            getline(input_data, line);
            vstring.push_back(line);
            line_num++;
        }
        else{
            cout << line_num << endl;
            break;
        }
    }
    input_data.close();

    int THREAD_NUM = (line_num + LINE_PER_THREAD - 1) / LINE_PER_THREAD;
    pthread_t threads[THREAD_NUM];
    for(int i = 0; i < THREAD_NUM; i++){
        struct param *str_param = new param();
        str_param->vstr = vstring;
        str_param->offset = i * LINE_PER_THREAD;
        str_param->tidx = i;
        pthread_create(&threads[i], NULL, std_output, (void *) str_param);
    }

    for(int i = 0; i < THREAD_NUM; i++)
        pthread_join(threads[i], NULL);

    return 0;
}
  1. 读一个文本文件,首先统计一下文本行数;

  2. 按每行分1024行,计算一下一共需要多少线程; 计算的时候,可以使用公式(N + 1023) / 1024,其中N是该文本文件总行数;

  3. std_output是一个kernel函数,使用mutex锁,其中,根据偏移量offset来决定处理哪一部分数据。该程序仅仅是打印出某一部分包含多少行。

输出:

18207
 thread 0 has 1024 lines
 thread 1 has 1024 lines
 thread 2 has 1024 lines
 thread 3 has 1024 lines
 thread 4 has 1024 lines
 thread 5 has 1024 lines
 thread 6 has 1024 lines
 thread 7 has 1024 lines
 thread 8 has 1024 lines
 thread 9 has 1024 lines
 thread 10 has 1024 lines
 thread 11 has 1024 lines
 thread 12 has 1024 lines
 thread 13 has 1024 lines
 thread 14 has 1024 lines
 thread 15 has 1024 lines
 thread 16 has 1024 lines
 thread 17 has 799 lines