c++ 類內使用線程pthread std::thread

#include <iostream>
#include <pthread.h>

using namespace std;

class Test
{
public:
    Test();

    void print();

    void start();

private:
    pthread_t p_t;

    static void * StartThread(void *arg);
};

Test::Test()
{

}

void Test::print()
{
    cout<<"This is thread......"<<sum<<endl;
}

void Test::start()
{
    pthread_create(&p_t, NULL, StartThread, (void *)this);
}

void *Test::StartThread(void *arg)
{
    Test *t = (Test *)arg;

    t->print();
}

int main(int argc, char *argv[])
{
    cout << "Hello World!" << endl;
    Test t;
    t.start();

    return 0;
}

 

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

using namespace std;

class Test {
public:
    Test();

    void print();

    void start();

    void stop();

private:
    thread p_t;

    void StartThread();
    bool stopFlag;
};

Test::Test()
{
    stopFlag = false;
}

void Test::print()
{
    cout<<"This is thread......"<<endl;
}

void Test::start()
{
    p_t = thread(&Test::StartThread, this);
}

void Test::stop()
{
    stopFlag = true;
    cout<<"thread stop......"<<endl;
}

void Test::StartThread()
{
    while (true) {
        if(!stopFlag)
            print();
    }
}

int main(int argc, char* argv[])
{
    cout << "Hello World!" << endl;
    Test t;
    t.start();
    usleep(5*1000*1000);
    t.stop();

    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章