카테고리 없음

[C++] How to call class methods in thread

sunshout 2015. 4. 6. 15:04

#include <pthread.h>

#include <stdio.h>

#include <unistd.h>



#include <thread>

#include <vector>


pthread_mutex_t g_NONSTOP;


class A

{

    private:

        std::vector<std::thread> threads;


    public:

        int numThread;


        A(int i) {

            numThread = i;

        }

        void test(int i) {


            printf("[tid:%d] called by TID:%lu\n", i, pthread_self());

        }


        void run(int i) {

            int tid = i;

            /*

             * Main loop

             * Call class method

             */

            while(1) {

                printf("[%d] run", tid);

                test(tid);

                sleep(tid+5);

            }

        }

        void start() {

            for(int i = 0; i < numThread; ++i) {

                threads.push_back(std::thread(&A::run, this, i));

            }

        }


};


void a_init()

{

    // get global configuration


    // create instance

    A *a = new A(4);

    a->start();

}


int main()

{

    a_init();


    pthread_mutex_init(&g_NONSTOP, NULL);

    pthread_mutex_lock(&g_NONSTOP);

    pthread_mutex_lock(&g_NONSTOP);


    return 0;

}



compile

g++ test.cpp -std=c++11 -lpthread