C++多线程

1. 创建新的线程

使用多线程必须包含<thread>头文件,类std::thread定义在该头文件中。通过创建std::thread对象即可创建新的线程,同时指定在该线程上运行的任务。该任务在新线程上运行直至返回,任务返回后线程同时结束。

void do_something();
std::thread my_thread(do_something);

创建新的线程时,必须显式地决定等待线程运行完成(join)或放任不管(detach)。一个线程只能调用join()一次,调用join()之后joinable()返回false。对std::thread对象调用detach()将使线程在后台运行,没有直接途径可与其通信。

2. 向线程传递参数

向线程中的函数传递参数时,参数被复制到线程的内部存储空间,然后传递给可调用对象或函数。

void f(int a, std::string const& s);
std::thread t(f, 3, "hello");

3. 获取CPU硬件线程数

获取CPU硬件线程数:std::thread::hardware_concurrency(),对多核心系统来说可能返回CPU核心数。

4. 线程标识符

线程标识符(identifier)是std::thread::id类型,可以通过关联的std::thread对象调用成员函数get_id()获取。当前线程的标识符也可以通过调用std::this_thread::get_id()获取。std::thread::id对象可以被复制和比较,如果两个std::thread::id相等,则它们代表相同的线程,或者都指向“空线程”(not any thread)。

5. 互斥量mutex

使用std::mutex和std::lock_guard必须包含<mutex>头文件。C++17中引入了增强版的lock guard——std::scoped_lock。Mutex保护数据的机理是使线程挂起!

In C++, you create a mutex by constructing an instance of std::mutex, lock it with a call to the lock() member function, and unlock it with a call to the unlock() member function. But it isn’t recommended practice to call the member functions directly, because this means that you have to remember to call unlock() on every code path out of a function, including those due to exceptions. Instead, the Standard C++ Library provides the std::lock_guard class template, which implements that RAII idiom for a mutex; it locks the supplied mutex on construction and unlocks it on destruction, ensuring a locked mutex is always correctly unlocked.

一个完整的例子

#include<iostream>
#include<thread>
#include<mutex>
#include<vector>
std::mutex m;
int a=0;

void func(int n) {
	std::cout<<"In thread "<<n<<" , before lock guard a = "<<a<<std::endl;
	std::lock_guard<std::mutex> guard(m);
	a++;
	std::cout<<"In thread "<<n<<" , after lock guard a = "<<a<<std::endl;
	std::cout<<"Now waiting in thread "<<n<<" for 200 ms.\n";
	_sleep(200);
	std::cout<<"Thread "<<n<<"  ended!!!\n";
}

int main() {
	int core_num = std::thread::hardware_concurrency();
	std::vector<std::thread> tv(core_num);
	std::cout<<"There are "<<core_num<<" cores on my computer.\n";
	for(int i=0; i<core_num; i++){
		tv[i]=std::thread(func, i);
// tv[i].join(); //if join here, all thread will run in line, one after another
	}

	for(int i=0; i<core_num; i++){
		tv[i].join();
	}
	
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值