#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
void f1(int n)
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 1 executing\n";
++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));
}
}
class foo
{
public:
void bar()
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 3 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
class baz
{
public:
void operator()()
{
for (int i = 0; i < 5; ++i) {
std::cout << "Thread 4 executing\n";
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int n = 0;
};
int main()
{
int n = 0;
foo f;
baz b;
std::thread t1; // t1 is not a thread
std::thread t2(f1, n + 1); // 值传递
std::thread t3(f2, std::ref(n)); // 引用传递
std::thread t4(std::move(t3)); // t4运行t3,t3不再运行
std::thread t5(&foo::bar, &f); // t5 在对象f上运行foo类的bar()函数
std::thread t6(b);
// t6 在对象 b 的一个副本上运行baz类的operator()()函数
//重载运算符(operator())
t2.join();
t4.join();
t5.join();
t6.join();
std::cout << "Final value of n is " << n << '\n';
std::cout << "Final value of f.n (foo::n) is " << f.n << '\n';
std::cout << "Final value of b.n (baz::n) is " << b.n << '\n';
}
C++多线程的简单创建
最新推荐文章于 2024-09-02 10:39:14 发布
本文详细介绍了C++中如何使用线程(包括std::thread和成员函数重载)实现并发,展示了f1, f2, foo::bar和baz::operator()的执行情况。通过值传递、引用传递和移动构造,探讨了数据共享与内存管理。最后,总结了主线程与线程间的数据同步与最终结果。
摘要由CSDN通过智能技术生成