C++11中5种创建线程方法

在本文中,我们将讨论如何使用std::thread在c++ 11中创建线程。

1.C++11中5种创建线程方法

  1. 函数指针——这是创建线程的基本形式。
  2. Lambda函数
  3. 仿函数(函数对象)
  4. 非静态成员函数
  5. 静态成员函数
    注意:如果我们同时创建多个线程,它不能保证哪个线程会先启动。
如何在Linux上编译:g++ -std =c++11 sample.cpp -lpthread

1.1函数指针

#include <thread>
#include <iostream>

void fun(int x)
{
	while(x-->0)
	{
		std::cout<< x<<std::endl;
	}
}
int main()
{
	std::thread t1(fun, 11);
	t1.join();
	return 0;
}

1.2Lambda函数

#include <thread>
#include <iostream>
using namespace std;

int main()
{
		auto fun = [](int x){
			while (x-- >0)
			{
				cout << x << endl;
			}
	};
	std::thread t(fun, 10);
	t.join();
	return 0;
}

我们可以在线程创建时直接使用lambda

#include <thread>
#include <iostream>
using namespace std;

int main()
{
	std::thread t([](int x){
			while (x-- >0)
			{
				cout << x << endl;
			}
	}, 10);
	t.join();
	return 0;
}

1.3仿函数

#include <thread>
#include <iostream>
using namespace std;

class Base
{
public:
	void operator()(int x)
	{
		while(x-->0)
		{
			cout<<x<<endl;
		}
	}
};
int main()
{
	std::thread t(Base(), 10);
	t.join();
	return 0;
}

1.4非静态成员函数

#include <thread>
#include <iostream>
using namespace std;

class Base
{
public:
	void run(int x)
	{
		while(x-->0)
		{
			cout<<x<<endl;
		}
	}
};
int main()
{
	Base b;
	std::thread t(&Base::run, &b, 10);
	t.join();
	return 0;
}

1.5静态成员函数

#include <thread>
#include <iostream>
using namespace std;

class Base
{
public:
	static void run(int x)
	{
		while(x-->0)
		{
			cout<<x<<endl;
		}
	}
};
int main()
{
	std::thread t(&Base::run, 10);
	t.join();
	return 0;
}

2.区分线程

每个std::thread对象都有一个相关联的ID,我们可以使用成员函数std::thread::get_id(),得到关联线程对象的id。使用std::this_thread::get_id()获取当前线程的ID。

#include <iostream>
#include <thread>
void thread_function()
{
    std::cout<<"Inside Thread :: ID  = "<<std::this_thread::get_id()<<std::endl;    
}
int main()  
{
    std::thread threadObj1(thread_function);
    std::thread threadObj2(thread_function);
 
    if(threadObj1.get_id() != threadObj2.get_id())
        std::cout<<"Both Threads have different IDs"<<std::endl;
        std::cout<<"From Main Thread :: ID of Thread 1 = "<<threadObj1.get_id()<<std::endl;    
    
    std::cout<<"From Main Thread :: ID of Thread 2 = "<<threadObj2.get_id()<<std::endl;    
 
    threadObj1.join();    
    threadObj2.join();    
    return 0;
}

参考目录

https://www.youtube.com/watch?v=hCvc9y39RDw
https://thispointer.com/c-11-multithreading-part-1-three-different-ways-to-create-threads/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值