#include "iostream"
#include "thread"
#include <utility>
#include <chrono>
#include <functional>
#include <atomic>
using namespace std;
void task()
{
cout << "thread" <<endl;
}
void f1(int n)
{
for(int i = 0; i < 5; i++)
{
cout << "f1 thread " << n <<endl;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
void f2(int& n)
{
for(int i = 0; i < 5; i++)
{
cout << "f2 thread executing " << endl ;
++n;
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
int main()
{
int n = 0;
thread t1;
thread t2(f1, n+ 1);
thread t3(f2, std::ref(n));
thread t4(std::move(t3));// t4 is now running f2(). t3 is no longer a thread
t2.join();
t4.join();
cout << "final value of n is " << n << endl;
getchar();
return 0;
}
C++ thread common
最新推荐文章于 2025-12-21 00:03:36 发布
这是一个C++示例,展示了如何使用std::thread创建并管理多个线程。示例中定义了task()、f1()和f2()三个线程任务,f2()通过引用传递参数并修改其值。程序创建了四个线程,t2和t4分别调用f1和f2,t3被移到t4后执行。最后输出n的最终值,演示了线程间的同步和数据共享。
5819

被折叠的 条评论
为什么被折叠?



