码迷,mamicode.com
首页 > 编程语言 > 详细

C++11多线程std::thread 调用某个类中函数的方法

时间:2016-06-17 14:07:18      阅读:6420      评论:0      收藏:0      [点我收藏+]

标签:

 

  当我们在利用thread创建一个线程,希望单独开线程,运行某个函数的时候,我们只要在主线程中,使用 std::thread(函数名,函数参数)就可以了
(如果不明白,请参阅:“C++11多线程std::thread的简单使用”)

 然而,有时候我们想开一个线程,运行一个类里面的某个函数。

譬如: 我们有一个class love,里面有一个成员函数 shit(int)

如果我们想单开一个线程,运行shit这个函数,应该怎么办呢?

简单的代码如下:

 

#include "stdafx.h"

#include <chrono>    // std::chrono::seconds
#include <iostream>  // std::cout
#include <thread>    // std::thread, std::this_thread::sleep_for




class love
{
public:
    love();
    ~love();

    void shit(int ding);
};

love::~love()
{
}


void love::shit(int ding)
{
    std::cout << ding << " hahaha " << std::endl;

}
/*
* ===  FUNCTION  =========================================================
*         Name:  main
*  Description:  program entry routine.
* ========================================================================
*/
int main(int argc, const char *argv[])
{

    love abc;
std::thread tt(&love::shit,5);   

    tt.join();return;
}  /* ----------  end of function main  ---------- */

我们发现完全编译不过啊!!有木有!

我们看看主程序,我们先定一个love类的对象abc

然后使用 

std::thread tt(&love::shit,5); 

希望开线程,调用love类里面的shit 函数,传递参数 5 。 

但是编译不通过。

因为类里面的函数,没有对象,怎么能够调用呢? 所以编译错误。。。

 

因此,我们使用

std::thread tt(&love::shit,abc,5); 

我们把对象也传递进去,这样编译就通过了。。。

 

 

PS: 把“对象”传递进去。。。我的天哪! 丧心病狂啊! 对象进去了,我还得再找对象了啊。。。

 

C++11多线程std::thread 调用某个类中函数的方法

标签:

原文地址:http://www.cnblogs.com/tinysun/p/5593702.html

(3)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!