C++:多线程std::thread

C++:多线程std::thread

  • 1. 线程的创建和终止
  • 2. 线程的参数传递
  • 3.线程和进程的身份标识

1. 线程的创建和终止

  main函数中,创建线程并控制线程结束:

#include 
#include 
#include 
using namespace std;
 
void fac() {
	while(true) {
		cout << "-- child thread ..." << endl;
		sleep(1);
	}
}
 
int main() {
	thread* th1 = new thread(fac);
	sleep(5);
	th1->detach();
	return 0;
}
  1. 创建线程:thread* th1 = new thread(fac);
  2. 创建线程传入的参数是函数:void fac();
  3. 在主函数中结束线程:th1->detach();

2. 线程的参数传递

  main函数中的变量传递到创建的线程中,让创建的线程修改main函数中的这些变量:

#include 
#include 
#include 
using namespace std;
 
void fac(int& arg1, int arg2[]) {
	arg1 = 0;
	arg2[1] = 0;
}
 
int main() {
	int arg1 = -1;
	int arg2[3] = {-1, -1, -1};
	thread* th1 = new thread(fac, ref(arg1), arg2);
	th1->join();
	cout << arg1 << endl;
	cout << arg2[1] << endl;
	return 0;
}
  1. 传递基本数据结构(如int)时,要使用std::ref()
  2. 使main函数等待th1线程结束后再继续执行:th1->join();

3.线程和进程的身份标识

  查看主线程和子线程的线程ID和进程ID:

#include 
#include 
#include 
using namespace std;
 
void fac() {
	cout << "The process ID of child thread:" << getpid() << endl;
	cout << "The thread ID of child thread:" << this_thread::get_id() << endl;
}
 
int main() {
	cout << "The process ID of main thread:" << getpid() << endl;
	cout << "The thread ID of main thread:" << this_thread::get_id() << endl;
	thread* th1 = new thread(fac);
	th1->join();
	return 0;
}
  1. 两个线程的进程ID是相同的。
  2. 两个线程的线程ID不同。

你可能感兴趣的:(C++)