C++之thread的简单使用示例

1、全局函数传入thread

#include 
#include 
#include 

void threadWork(std::string content, int counts)
{
    for (int i = 0; i < counts; ++i) {
        std::cout << content << i << std::endl;
    }
}

int main() {
    std::thread worker(threadWork, std::string("work on thread, index: "), 10);
    worker.join();
    return 0;
}

C++之thread的简单使用示例_第1张图片

2、类成员函数传入thread

#include 
#include 
#include 

class MyClass {
public:
    void doSomething(std::string content, int counts) {
        for (int i = 0; i < counts; ++i) {
            std::cout << content << i << std::endl;
        }
    }
};

int main() {
    MyClass* obj = new MyClass;
    std::thread worker(&MyClass::doSomething, obj, std::string("doSomething on thread, index: "), 10);
    worker.join();
    return 0;
}

C++之thread的简单使用示例_第2张图片

3、lambda表达式(匿名函数)传入thread

#include 
#include 
#include 

int main() {
    std::thread worker(
        [](std::string content, int counts)
        {
            for (int i = 0; i < counts; ++i) {
                std::cout << content << i << std::endl;
            }
        }, std::string("lambda on thread, index: "), 10);
    worker.join();
    return 0;
}

C++之thread的简单使用示例_第3张图片

你可能感兴趣的:(C++笔记,c++,多线程,thread)