天天看点

C++多线程,创建线程std::thread

#include <iostream>
#include <thread>
#include <unistd.h>
#include <map>


class A {
    private:
        int m_a = 100;
        std::thread m_t;
        bool m_run_flag = true;
    public:
        int run_1() {
            while(m_run_flag) {
                std::cout << "A: run_1" << std::endl;
                std::cout.flush();
                sleep(1);
            }
            return 0;
        }
        int run_2(std::string name, int num, std::string ope) {
            m_a = num;
            while(m_run_flag) {
                if(ope == "+") {
                    m_a++;
                }else if(ope == "-") {
                    m_a--;
                }
                std::cout << "A:" << name << "  m_a:" << m_a <<std::endl;
                std::cout.flush();
                sleep(1);
            }
            return 0;
        }
        static int run_3(std::string name, std::string ope) {
            int a = 100;
            while(true) {
                if(ope == "+") {
                    a++;
                }else if(ope == "-") {
                    a--;
                }
                std::cout << "A:" << name << "  a:" << a <<std::endl;
                std::cout.flush();
                sleep(1);
            }
            return 0;
        }
        int startThread() {
            m_t = std::thread(&A::run_1, this);
            m_t.detach();
            return 0;
        }
        int startThread(std::string str, int num, std::string ope) {
            m_t = std::thread(&A::run_2,this, str, 100, ope);
            m_t.detach();
            return 0;
        }
        // int startThread(std::string str, std::string ope) {
        //     m_t = new std::thread(run_3, str, ope);
        //     return 0;
        // }
        int startThread(std::string str, std::string ope) {
            m_t = std::thread(A::run_3, str, ope);
            m_t.detach();
            return 0;
        }
        // int startThread(std::string str, std::string ope) {
        //     m_t = new std::thread(&A::run_3, str, ope);
        //     return 0;
        // }

        int deleteThread() {
            m_run_flag = false;
            return 0;
        }
};

int main() {

    A *a_1 = new A();
    a_1->startThread("a_1", "+");
    A *a_2 = new A();
    a_2->startThread("a_2", "-");

    A * b_1 = new A();
    b_1->startThread("b_1", 200, "+");
    A * b_2 = new A();
    b_2->startThread("b_2", 200, "-");

    A * c = new A();
    c->startThread();

    sleep(6);
    a_1->deleteThread();
    b_1->deleteThread();

    while(1);

    return 0;
}