c++多线程笔记1

参考:https://baptiste-wicht.com/posts/2012/03/cpp11-concurrency-part1-start-threads.html#

1. 创建线程

使用std::thread构造线程,当你创建一个线程,需要给线程代码,其中一个选择便是传函数指针。所有的线程工具都在thread 头文件中。

#include <thread>
#include <iostream>

void hello(){
    std::cout << "Hello from thread " << std::endl;
}

int main(){
    std::thread t1(hello);
    t1.join(); 
/*Calling this function forces current to wait for the other one.
* the main thread has to wait for the thread t1 to finish.
*/
    return 0;
}

这里的 join() 使得main线程需要等待t1线程结束。如果没有调用join(),结果将不确定,因为main线程可能在t1线程结束前从main函数返回。

2. 线程区分

每个线程都有一个id供我们区分,std::thread类有一个get_id()函数能返回特定线程的id号。需要 std::this_thread命名空间的 get_id()函数。

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

void hello(){
    std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}

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

    for(int i = 0; i < 5; ++i){
        threads.push_back(std::thread(hello));
    }

    for(auto& thread : threads){
        thread.join();
    }

    return 0;
}
/*输出:
*Hello from thread.139920874026752
*Hello from thread.139920882419456
*Hello from thread.139920890812160
*Hello from thread.139920899204864
*Hello from thread.139920907597568
*/

3. lambda 

当代码量比较小而不用另一个函数描述时候,可以用lambda去定义:

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

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

    for(int i = 0; i < 5; ++i){
        threads.push_back(std::thread([](){
            std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
        }));
    }

    for(auto& thread : threads){
        thread.join();
    }

    return 0;
}

实现了同样的功能,不过是用lambda 表达代替了函数指针。

猜你喜欢

转载自www.cnblogs.com/Shinered/p/9078844.html