c++ 线程创建方法

 

c++创建线程

普通函数创建线程

#include <iostream>
#include <thread>
void func()
{
	std::cout << "hello world!" << std::endl;
}

int main()
{
    std::thread thread_tmp(&func);
    thread_tmp.join();

    return 0;
}

类外部创建类非静态成员函数的线程

class Test
{
public:
	void func()
	{
		std::cout << "hello world!" << std::endl;
	}
};

int main()
{
    Test my_test;
    std::thread thread_tmp =std::thread(std::bind(&Test::func, my_test));
    thread_tmp.join();
    system("pause");

    return 0;
}

类外部创建类静态成员函数的线程

#include<iostream>
#include<thread>

class A 
{ 
public: 
	static void fun() 
	{
		std::cout<< "hello world";
	}
};

int main()
{
	std::thread t=std::thread(A::fun);
	system("pause");
    return 0;
}

类内部创建线程

静态函数

class Test
{
public:
	Test()
	{
		init();
	}
	static void init()
	{
		std::thread thread_tmp(&func);
		thread_tmp.join();
	}
	static void func()
	{
		std::cout << "hello world!" << std::endl;
	}
};

int main()
{
	Test my_test;
	system("pause");

    return 0;
}

非静态函数(std::bind)

class Test
{
public:
	Test()
	{
		init();
	}
	void init()
	{
		std::thread thread_tmp = std::thread(std::bind(&Test::func,this));
		thread_tmp.join();
	}
	void func()
	{
		std::cout << "hello world!" << std::endl;
	}
};

int main()
{
    Test my_test;
    system("pause");

    return 0;
}

 

编辑于 2019-08-12

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值