当我们在利用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: 把“对象”传递进去。。。我的天哪! 丧心病狂啊! 对象进去了,我还得再找对象了啊。。。
原文链接: https://www.cnblogs.com/tinysun/p/5593702.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/235348
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!