<一>通过thread类编写C++多线程程序
  xs9mrAcZVTZn 2023年11月02日 30 0
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" <<this_thread::get_id() << 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::cout<<this_thread::get_id()<<std::endl;//main thrad id

	//创建一个线程对象,传入一个线程函数,即函数指针,新线程就开始运行了
	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(); 主线程结束,整个进程结束,所有子线程都自动结束

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月08日 0

暂无评论

推荐阅读
  8Tw5Riv1mGFK   2024年05月01日   82   0   0 C++
  BYaHC1OPAeY4   2024年05月08日   58   0   0 C++
  yZdUbUDB8h5t   2024年05月05日   44   0   0 C++
  oXKBKZoQY2lx   2024年05月17日   62   0   0 C++
xs9mrAcZVTZn