刷野打怪上王者·C++篇·第22期·多线程处理

参考链接

RUNOOB.COM

多线程处理

    在电脑中可以进行多任务处理,其中多任务的处理方式分为两种:多进程多线程多进程是程序的并发执行;多线程是同一程序判断并发执行。

实例程序

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>

void f1(int n) 
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread " << n << " executing\n";
		std::this_thread::sleep_for(std::chrono::milliseconds(10)); //线程休眠一段时间
	}
}

void f2(int& n)
{
	for (int i = 0; i < 5; ++i) {
		std::cout << "Thread 2 executing\n";
		++n;
		std::this_thread::sleep_for(std::chrono::milliseconds(10)); //线程休眠一段时间
	}
}

int main()
{
	int iPara = 0;
	std::thread thread1;             // thread1不是线程
	std::thread thread2(f1, iPara + 1); // 想函数内传递iPara + 1
	std::thread thread3(f2, std::ref(iPara)); // 通过参考的方式传递值
	std::thread thread4(std::move(thread3)); // thread4现在运行f2. thread3不在是线程
	thread2.join();
	thread4.join();
	std::cout << "Final value of n is " << iPara << '\n';
	getchar();
}

运行结果

Thread Thread 2 executing
1 executing
Thread 1Thread 2 executing
 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Thread 2 executing
Thread 1 executing
Final value of n is 5

更多《计算机视觉与图形学》知识,可关注下方公众号:

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值