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 lock(mtx); // 加锁

++count; // 修改共享计数器

}

}

int main() {

std::thread t1(increment); // 创建两个线程,同时修改共享计数器

std::thread t2(increment); // 创建两个线程,同时修改共享计数器

(); // 等待线程结束

(); // 等待线程结束

std::cout << "Count = " << count << std::endl; // 输出共享计数器的值

return 0;

}


本文标签: 线程 函数 程序 共享 网页