c++ 简单使用线程

引言

突发奇想从0生成90亿的数字到文件,类似于彩虹表,出于性能考虑,选择了C++,顺便复习一下多线程。

代码

process

#include<iostream>
#include <thread>
#include <vector>
#include <map>
#include <fstream>

using namespace std;
const bool process = true; // 是否显示进度
const unsigned long long target = 9000000000; // 目标数字
const unsigned int thread_num = 16; // 线程数
const unsigned long long pre_t = target / thread_num; // 每个线程分配额度

map<unsigned long long, unsigned long long> result; // 进度存储

void in_thread(unsigned long long f1, unsigned long long f2) { // 子线程
//    cout << "thread" << this_thread::get_id << ":" << f1 << "\t" << f2 << endl << flush;
    ofstream outfile("d:\\target\\" + to_string(f1) + ".txt", ios::app);
    for (unsigned long long cur = f1; cur <= f2; cur++) {
        if (process) result[f1] = cur;
        outfile << cur << endl;
    }
    outfile.close();
}

void calc_process() {
    while (1) {
        int ok = 0;
        system("cls"); // linux 可用clear
        for (unsigned long long i = 1; i <= thread_num; i++) {
            cout << "thread-" << i << ":\t\tcur:" << result[i * pre_t - pre_t] << "\t\t" << "target:" << i * pre_t - 1
                 << endl;
            if (result[i * pre_t - pre_t] >= i * pre_t - 1)ok++;
        }
        cout <<"Done:"<< ok << flush;
        for (int i = 0; i < 50000000; i++);
        if (ok == 16)break;
    }
}

int main() {

    vector<thread> thread_pool;
    for (int i = 1; i <= thread_num; i++) {
        unsigned long long f1 = pre_t * i - pre_t;
        unsigned long long f2 = pre_t * i - 1;
        result[f1] = 0;
        thread_pool.push_back(thread(in_thread, f1, f2));
        for (int j = 0; j < 10000000; j++);
    }
    if (process) thread_pool.push_back(thread(calc_process));
    for (auto &t: thread_pool) {
        if (t.joinable()) {
            t.join();
        }
    }
}

线程部分

引入头文件thread

auto t = thread(thread_name, arg1, arg2,......); 第一个参数是名称,后面的是传递给线程的参数
t.join();

最后的join()是为了确保所有线程结束,如果主线程结束了,子线程还没跑完,可能会发生异常terminate called without an active exception

代码平台

  • 编译器:MinGW w64 11.0
  • 操作系统:windows

小思考

如果我这个代码运行下去的话,最终会生成多大的文件呢?

其实手比脑子快了,没思考这个问题,就写上代码了,这个习惯不太好。

评论 0

还没有评论,来说点什么吧。

提交后需要审核才会公开。