📜  多线程 - C++ 代码示例

📅  最后修改于: 2022-03-11 14:44:57.229000             🧑  作者: Mango

代码示例2
#include 
#include 
#include 

void task1() {

    /* count from 1 to 10 with 1 second pause in between */
    for(int i = 1; i <= 10; ++i) {

        /* simulating a length process, sleeping for 1 second */
        std::this_thread::sleep_for(std::chrono::seconds(1));

        std::cout << "TASK 1: " << i << std::endl;

    }

}

void task2() {

    /* count from 1 to 10 with 2 seconds pause in between */
    for(int i = 1; i <= 10; ++i) {

        /* simulating a length process, sleeping for 2 seconds */
        std::this_thread::sleep_for(std::chrono::seconds(2));

        std::cout << "TASK 2: " << i << std::endl;

    }

}

int main(int count, char* args[]) {

    /* start task 1 from a different thread */
    std::thread t1{task1};

    /* start task 2 from a different thread */
    std::thread t2{task2};

    /* wait for task1 and task2 to finish running */
    t1.join();
    t2.join();

    return 0;

}