thread3.cpp 712 Bytes
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <thread>
#include <vector>
#include <unistd.h> // 用于sleep函数

// 线程将要执行的函数
void print_hello(int thread_id) {
    std::cout << "Hello World! It's me, thread #" << thread_id << "!\n";
    sleep(1); // 模拟长时间运行的任务
    std::cout << "Thread #" << thread_id << " is finished.\n";
}

int main() {
    std::vector<std::thread> threads;
    for(int i = 0; i < 2; ++i) {
        std::cout << "In main: creating thread #" << i << "\n";
        threads.push_back(std::thread(print_hello, i));
    }

    // 等待所有线程完成
    for(auto& th : threads) {
        th.join();
    }

    std::cout << "Main completed. Exiting.\n";
    return 0;
}