C++启动线程的方法

(1)函数指针
情况一:主线程有join,正常执行

#include 
#include 

void work(int num) {
    while(num-- > 0) {
        std::cout << num << std::endl;
    }
}

int main() {
    std::thread t(work, 5);
    t.join();
    return 0;
}

情况二:主线程没有join,出现core dump

#include 
#include 

void work(int num) {
    while(num-- > 0) {
        std::cout << num << std::endl;
    }
}

int main() {
    std::thread t(work, 5);
    //t.join();
    return 0;
}

(2)lambda表达式

#include 
#include 

int main(int argc, char* argv[]){
    std::thread t([](int num){
        while (num-- > 0) {
	        std::cout << num << std::endl;
	    }
    }, 5);
    t.join();
    return 0;
}

(3)仿函数

#include 
#include 
#include 

class Demo {
public:
    void operator()(int num) {
        while(num-- > 0) {
            std::cout << num << std::endl;
        }
    }
};

int main(int argc, char* argv[]) {
    std::thread t(Demo(), 5);
    t.join();
    return 0;
}

(4)静态成员函数

#include 
#include 

class Demo {
public:
    static void work(int num){
        while(num-- > 0) {
            std::cout << num << std::endl;
        }
    }
};

int main(int argc, char* argv[]) {
    std::thread t(&Demo::work, 5);
    t.join();
    return 0;
}

(5)非静态成员函数

#include 
#include 

class Demo {
public:
    void work(int num){
        while(num-- > 0) {
            std::cout << num << std::endl;
        }
    }
};

int main(int argc, char* argv[]) {
    Demo d;
    std::thread t(&Demo::work, &d, 5);
    t.join();
    return 0;
}

你可能感兴趣的:(C/C++,c++,开发语言)