欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

C++11通过函数指针创建线程

程序员文章站 2022-07-05 18:11:27
...
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<string>
#include<thread>

using namespace std;

void func() {
	cout << "my thread::func(),thread id is:" << this_thread::get_id() << endl;
}

void func1(string s) {
	cout << "my thread::func1(),the arg is " << s << " thread id is:" << this_thread::get_id() << endl;
}

void func2(string &s) {
	cout << "&s:" << &s << endl;
	cout << "my thread::func2(),the arg is " << s << " ,thread id is:" << this_thread::get_id() << endl;
}

void func3(int a, int b) {
	cout << "my thread::func3()" << a + b << endl;
}

int main(){
	thread th = thread(func);
	th.join();
	cout << "main thread::func(),thread id is:" << this_thread::get_id() << endl;
	cout << endl;

	thread th1 = thread(func1, "渣渣猫");
	th1.join();
	cout << endl;

	string str = "土拨鼠";
	thread th2 = thread(func2, std::ref(str));
	th2.join();
	cout << "&s:" << &str << endl;
	cout << "main thread::func2(),the arg is " << str << " ,thread id is:" << this_thread::get_id() << endl;
	cout << endl;

	thread th3 = thread(func3, 5, 6);
	th3.join();

	system("pause");
	return 0;
}

C++11通过函数指针创建线程