参考链接
多线程处理
在电脑中可以进行多任务处理,其中多任务的处理方式分为两种:多进程和多线程。多进程是程序的并发执行;多线程是同一程序判断并发执行。
实例程序
#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
更多《计算机视觉与图形学》知识,可关注下方公众号: