C++多线程(一)

直接总结多线程写法:

1.直接启动函数:

#include <iostream>
#include <windows.h>
#include <thread>

void fun1(){
    
    
	for(int i = 0; i < 3; i++){
    
    
		std::cout << "fun1" << std::endl;
		Sleep(500);
	}
}

void fun2(){
    
    
	for(int i = 0; i < 3; i++){
    
    
		std::cout << "fun2" << std::endl;
		Sleep(500);
	}
}
int main(){
    
    
	std::thread mythread1(fun1);
	std::thread mythread2(fun2);
	mythread1.join();
	mythread2.join();
	return 0;
}

运行结果:
在这里插入图片描述

2.lambd表达式:

#include <iostream>
#include <windows.h>
#include <thread>

void fun1(){
    
    
	for(int i = 0; i < 3; i++){
    
    
		std::cout << "fun1" << std::endl;
		Sleep(500);
	}
}
int main(){
    
    
	
	std::thread mythread1([](){
    
    
		for(int i = 0; i < 3; i++){
    
    
			std::cout << "lambd()" << std::endl;
			Sleep(500);
		}
	});
	fun1();
	mythread1.join();
	return 0;
}

运行结果:

在这里插入图片描述

3.类启动, 重写operator():

#include <iostream>
#include <windows.h>
#include <thread>

void fun1(){
    
    
	for(int i = 0; i < 3; i++){
    
    
		std::cout << "fun1" << std::endl;
		Sleep(500);
	}
}

class A{
    
    
public:
	void operator()(){
    
    
		for(int i = 0; i < 3; i++){
    
    
			std::cout << "operator()" << std::endl;
			Sleep(500);
		}
	}
};

int main(){
    
    
	A a;
	std::thread mythread1(a);
	fun1();
	mythread1.join();
	return 0;
}

运行结果:
在这里插入图片描述
4.类成员函数指针做线程函数:

#include <iostream>
#include <windows.h>
#include <thread>

void fun1(){
    
    
	for(int i = 0; i < 3; i++){
    
    
		std::cout << "fun1" << std::endl;
		Sleep(500);
	}
}

class B{
    
    
public:
	void thread_fun(int num){
    
    
		for(int i = 0; i < num; i++){
    
    
			std::cout << "thread_fun()" << std::endl;
			Sleep(500);
		}
	}
};

int main(){
    
    
	B b;
	std::thread mythread1(&B::thread_fun,&b, 4);
	fun1();
	mythread1.join();
	return 0;
}

运行结果:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_42096202/article/details/114027543