多线程
【摘要】 多线程
1.介绍
多线程是指在一个程序中同时运行多个线程来完成不同的任务。每个线程都有自己的指令指针、寄存器和栈,但是它们共享同一个地址空间和其他资源,如打开的文件和全局变量
C++11 引入了对多线程的支持,包括 std::thread
类和相关的同步原语,如 std::mutex
和 std::condition_variable
。使用这些类和函数,可以在 C++ 程序中创建和管理多个线程
2.例子
下面是一个简单的示例,演示如何在 C++ 中创建和使用多个线程:
#include <iostream>
#include <thread>
void print(int n) {
for (int i = 0; i < n; ++i) {
std::cout << "Hello from thread " << std::this_thread::get_id() << std::endl;
}
}
int main() {
std::thread t1(print, 3);
std::thread t2(print, 5);
t1.join();
t2.join();
return 0;
}
在这个示例中,我们定义了一个 print()
函数,它接受一个整数参数 n
,并输出 n
行文本。在 main()
函数中,我们创建了两个线程 t1
和 t2
,它们分别执行 print(3)
和 print(5)
。然后我们调用 join()
方法来等待两个线程结束。
这段代码的一个可能的输出结果是:
Hello from thread 1
Hello from thread 1
Hello from thread 1
Hello from thread 2
Hello from thread 2
Hello from thread 2
Hello from thread 2
Hello from thread 2
或者
Hello from thread 2
Hello from thread 2
Hello from thread 2
Hello from thread 2
Hello from thread 2
Hello from thread 1
Hello from thread 1
Hello from thread 1
具体的输出顺序取决于线程的调度顺序,这是不确定的
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)