C ++:在线程内运行类成员函数

时间:2019-06-07 05:49:09

标签: c++

请考虑以下示例C ++代码:

#include <cstdio>
#include <string> 
#include <cstring>
#include <iostream>
#include <thread>

using namespace std;

class TriCycle{
    private:
        int YearBuilt;
        int Speed;
    public:
        int getSpeed() { return Speed; }
        TriCycle(int x);
        void Pedal();
};

TriCycle::TriCycle(int x){
    Speed = x;
    puts("Entering front yard TriCycle Race..");
}

void TriCycle::Pedal(){
    puts("Pedalling..");
    Speed++;
}


void sayhi(){
    puts("Hi!");
}

int main(){

    TriCycle Wichita(3);
    TriCycle * PtrWichita = &Wichita;
    printf("Current Speed %d\n", PtrWichita->getSpeed());

    thread t(sayhi);

    PtrWichita->Pedal();
    printf("Current Speed %d\n", PtrWichita->getSpeed());

    PtrWichita->Pedal(); // <-- this works
    printf("Current Speed %d\n", PtrWichita->getSpeed());

    //thread t3(PtrWichita->Pedal,this); // <--  fails
    //t3.join(); // <- this fails

    t.join();

}

我试图在线程中运行我的Pedal成员函数,显然我没有这样做。我很困惑,因为PtrWichita->Pedal()似乎运行正常。

请告诉我如何在线程内使用PtrWichita->Pedal()方法?预先感谢!

0 个答案:

没有答案