Skip to content

Commit

Permalink
feat: 增加线程任务
Browse files Browse the repository at this point in the history
  • Loading branch information
null-qwerty committed Feb 25, 2024
1 parent fe1013e commit a29dbe3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
31 changes: 31 additions & 0 deletions C++/thread/thread.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 1. 多次编译运行,观察输出结果。
* 2. 修改下面的代码,使得 a 的值等于 threadNum * 10000。只能修改 foo 函数,不能修改 main 函数,可以增加变量。
*/

#include <iostream>
#include <thread>
#include <vector>

const int threadNum = 10; // 线程数

void foo(int &a) {
for (int i = 0; i < 10000; i++) // 每个线程对 a 加 10000 次
a++;
return;
}

int main(int argc, char* argv[], char** env)
{
int a = 0; // 总计数器
std::vector<std::thread> threadVec;

for (int i = 0; i < threadNum; i++) // 创建 threadNum 个线程
threadVec.push_back(std::thread(foo, std::ref(a)));
for (int i = 0; i < threadNum; i++)
threadVec[i].join(); // 等待所有线程结束

std::cout << "a = " << a << std::endl; // 输出 a 的值

return 0;
}
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@

以下为可选:

+ 修改 `thread/thread.cpp` 中的代码
+ 实现一个进程间通信(IPC)框架
+ 压缩一张位图
+ 实现一个坐标系转换类
Expand Down

0 comments on commit a29dbe3

Please sign in to comment.