admin 管理员组文章数量: 1184232
2024年1月18日发(作者:网页显示xml文件内容)
C++11引入了std::thread库,用于在C++程序中实现多线程编程。std::thread库提供了一些类和函数,可以方便地创建和管理线程。
以下是std::thread库的一些基本用法:
创建线程
可以使用std::thread类的构造函数来创建一个线程。构造函数接受一个函数指针或可调用对象作为参数,该函数或对象将在新线程中运行。例如:
c
#include
#include
void foo() {
std::cout << "Hello from foo!" << std::endl;
}
int main() {
std::thread t(foo); // 创建一个新线程,运行foo函数
(); // 等待线程结束
return 0;
}
传递参数
可以向线程函数传递参数。例如:
c
#include
#include
void foo(int x) {
std::cout << "Hello from foo! x = " << x << std::endl;
}
int main() {
int x = 42;
std::thread t(foo, x); // 创建一个新线程,运行foo函数,并将x作为参数传递给它
(); // 等待线程结束
return 0;
}
获取线程ID
可以使用std::thread::get_id函数获取线程的ID。例如:
c
#include
#include
void foo() {
std::cout << "Hello from foo! Thread ID = " << std::this_thread::get_id()
<< std::endl;
}
int main() {
std::thread t(foo); // 创建一个新线程,运行foo函数
std::cout << "Main thread ID = " << std::this_thread::get_id() << std::endl;
(); // 等待线程结束
return 0;
}
线程同步
可以使用std::mutex和std::lock_guard等类来同步线程。例如:
c
#include
#include
#include
std::mutex mtx; // 互斥锁
int count = 0; // 共享计数器
void increment() {
for (int i = 0; i < 100000; ++i) {
std::lock_guard
++count; // 修改共享计数器
}
}
int main() {
std::thread t1(increment); // 创建两个线程,同时修改共享计数器
std::thread t2(increment); // 创建两个线程,同时修改共享计数器
(); // 等待线程结束
(); // 等待线程结束
std::cout << "Count = " << count << std::endl; // 输出共享计数器的值
return 0;
}
版权声明:本文标题:c++中thread的用法 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.roclinux.cn/b/1705566863a490250.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论