logo

创建一组线程

//Create a group of C++11 threads from the main program

#include <iostream>
#include <thread>

static const int num_threads = 10;

//This function will be called from a thread

void call_from_thread(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::thread t[num_threads];

    //Launch a group of threads
    for (int i = 0; i < num_threads; ++i) {
        t[i] = std::thread(call_from_thread, i);
    }

    std::cout << "Launched from the main\n";

    //Join the threads with the main thread
    for (int i = 0; i < num_threads; ++i) {
        t[i].join();
    }

    return 0;
}

或者使用vector

//Create a group of C++11 threads from the main program

#include <iostream>
#include <thread>
#include <vector>

//This function will be called from a thread

void func(int tid) {
    std::cout << "Launched by thread " << tid << std::endl;
}

int main() {
    std::vector<std::thread> th;

    int nr_threads = 10;

    //Launch a group of threads
    for (int i = 0; i < nr_threads; ++i) {
        th.push_back(std::thread(func,i));
    }

    //Join the threads with the main thread
    for(auto &t : th){
        t.join();
    }

    return 0;
}

编译:
g++ -std=c++11 -pthread thread.cpp

输出:

./a.out 
Launched by thread 6
Launched by thread 7
Launched by thread 8
Launched by thread 9
Launched by thread 5
Launched by thread 4
Launched by thread 3
Launched by thread 2
Launched by thread 1
Launched by thread 0
0 回复
需要 登录 后方可回复, 如果你还没有账号你可以 注册 一个帐号。