linuxC++开启10个线程,并传递一个参数
时间: 2023-12-14 11:37:08 浏览: 33
可以使用C++11中的std::thread库来开启线程,并通过lambda表达式传递参数。例如,以下代码将创建10个线程,每个线程打印传递的参数:
```c++
#include <iostream>
#include <thread>
#include <vector>
void print_arg(int arg) {
std::cout << "Thread " << std::this_thread::get_id() << " received argument: " << arg << std::endl;
}
int main() {
std::vector<std::thread> threads;
int arg = 42;
for (int i = 0; i < 10; i++) {
threads.emplace_back([arg, i]() { print_arg(arg + i); });
}
for (auto& t : threads) {
t.join();
}
return 0;
}
```
在上面的例子中,我们使用了一个std::vector来存储所有线程,然后使用emplace_back函数向其中添加线程。lambda表达式以值传递的方式捕获了外部变量arg和循环变量i,然后将它们相加传递给print_arg函数。最后,我们使用join函数等待所有线程完成。
相关问题
linuxC++开启10个线程,并传递一个参数
可以使用C++11的线程库来开启多个线程并传递参数。以下是一个简单的示例:
```cpp
#include <iostream>
#include <thread>
#include <vector>
void threadFunction(int threadId) {
std::cout << "Thread " << threadId << " started." << std::endl;
}
int main() {
std::vector<std::thread> threads;
// 创建10个线程并传递参数
for (int i = 0; i < 10; ++i) {
threads.push_back(std::thread(threadFunction, i));
}
// 等待所有线程执行完毕
for (auto& thread : threads) {
thread.join();
}
return 0;
}
```
在上面的代码中,我们使用 `std::vector` 来存储线程对象,并使用 `std::thread` 构造函数创建线程。构造函数的第一个参数是线程函数的指针,第二个参数是要传递给线程函数的参数。我们使用循环来创建10个线程,并将它们存储在 `threads` 向量中。然后我们使用另一个循环来等待所有线程执行完毕,并使用 `join()` 函数来等待线程结束。
linuxC++开启10个线程
下面是一个简单的示例代码,可以启动10个线程:
```c++
#include <iostream>
#include <thread>
void thread_function(int thread_id) {
std::cout << "Thread " << thread_id << " started" << std::endl;
// do some work here
std::cout << "Thread " << thread_id << " finished" << std::endl;
}
int main() {
std::thread threads[10];
for (int i = 0; i < 10; i++) {
threads[i] = std::thread(thread_function, i);
}
for (int i = 0; i < 10; i++) {
threads[i].join();
}
return 0;
}
```
在这个示例中,我们定义了一个名为`thread_function`的函数,它将被10个不同的线程调用。每个线程都传递一个不同的`thread_id`参数,以便我们可以区分每个线程的输出。
在`main`函数中,我们创建一个长度为10的线程数组,并使用循环来创建每个线程。每个线程都调用`thread_function`函数,并传递一个不同的`thread_id`参数。
最后,我们使用另一个循环来等待每个线程完成,并调用`join`函数。这确保了主线程等待所有子线程完成后再退出。
请注意,如果您的程序需要使用多线程,请确保正确地管理线程之间的竞争条件和同步。