<一>通过thread类编写C++多线程程序

C++语言层面多线程=>好处:跨平台 windows/linux

thread/mutex/condition_variable

lock_gurad/unique_lock

atomic/原子类型,基于CAS操作的原子类型 线程安全的

睡眠sleep_for

C++ thread => windows 平台用的createThread Linux用的pthread_create

简单示例1

#include <iostream>
#include <thread>

using namespace std;

void threadHandler() {

	//让子线程睡眠2秒
	std::this_thread::sleep_for(std::chrono::seconds(2));
	cout << "hello threadHandler" << endl;

}

void threadHandler2(int x,int y) {

	//让子线程睡眠2秒
	std::this_thread::sleep_for(std::chrono::seconds(2));
	cout << "hello threadHandler2 (x+y)=" << (x+y) << endl;

}


int main() {

	//创建一个线程对象,传入一个线程函数,新线程就开始运行了
	std::thread  thread1(threadHandler);

	//主线程等待子线程结束,主线程继续向下运行
	thread1.join();


	//创建一个线程对象,传入一个线程函数,新线程就开始运行了 ,传递参数
	std::thread  thread2(threadHandler2,100,200);

	//主线程等待子线程结束,主线程继续向下运行
	thread2.join();


	system("pause");
	return 1;
}

简单示例2

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

void threadHandler() {

	//让子线程睡眠2秒
	std::this_thread::sleep_for(std::chrono::seconds(2));
	cout << "hello threadHandler" << endl;

}

int main() {

	//创建一个线程对象,传入一个线程函数,新线程就开始运行了
	std::thread  thread1(threadHandler);
	system("pause");
	return 1;
}

简单示例3

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

void threadHandler() {

	//让子线程睡眠2秒
	std::this_thread::sleep_for(std::chrono::seconds(2));
	cout << "hello threadHandler" << endl;

}

void threadHandler2() {

	//让子线程睡眠4秒
	std::this_thread::sleep_for(std::chrono::seconds(4));
	cout << "hello threadHandler2" << endl;

}

int main() {

	//创建一个线程对象,传入一个线程函数,新线程就开始运行了
	std::thread  thread1(threadHandler);
        std::thread  thread2(threadHandler);
       //等待线程1,线程2结束
        thread1.join();
        thread2.join();
	system("pause");
	return 1;
}

小结:
一:怎么创建启动一个线程
std::thread定义一个线程对象,传入线程所需要的线程函数和参数,线程自动开启

二:子线程如何结束
子线程函数运行完成,那么线程就结束了

三:主线程如何处理子线程
1:等待thread线程结束,当前线程继续运行 thread.join();
2:设置thread线程为分离线程 thread.detach(); 主线程结束,整个进程结束,所有子线程都自动结束

原文链接: https://www.cnblogs.com/erichome/p/16975866.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    <一>通过thread类编写C++多线程程序

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/4938

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月4日 下午7:10
下一篇 2023年2月4日 下午7:10

相关推荐