#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; }
讀一個文本文件,首先統計一下文本行數;
按每行分1024行,計算一下一共需要多少線程; 計算的時候,可以使用公式(N + 1023) / 1024,其中N是該文本文件總行數;
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