c++循环创建10线程
时间: 2023-05-14 07:05:52 浏览: 142
可以使用pthread库来创建线程,以下是一个示例代码:
```c
#include <pthread.h>
#include <stdio.h>
void *thread_func(void *arg) {
int thread_num = *(int*)arg;
printf("Thread %d is running\n", thread_num);
pthread_exit(NULL);
}
int main() {
pthread_t threads[10];
int thread_args[10];
int i;
for (i = 0; i < 10; i++) {
thread_args[i] = i;
pthread_create(&threads[i], NULL, thread_func, &thread_args[i]);
}
for (i = 0; i < 10; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
这个程序会创建10个线程,每个线程都会打印出自己的编号。可以使用pthread_join函数来等待所有线程结束。
相关问题
c++ for循环创建线程
在 C++ 中,可以使用 for 循环来创建多个线程。以下是一个示例代码:
```cpp
#include <iostream>
#include <thread>
void threadFunction(int i) {
std::cout << "Thread " << i << " is running" << std::endl;
}
int main() {
const int numThreads = 5;
// 创建多个线程
std::thread threads[numThreads];
for (int i = 0; i < numThreads; ++i) {
threads[i] = std::thread(threadFunction, i);
}
// 等待所有线程完成
for (int i = 0; i < numThreads; ++i) {
threads[i].join();
}
return 0;
}
```
在上面的代码中,我们定义了一个 `threadFunction` 函数,它将作为每个线程的入口点。在 `main` 函数中,我们通过循环创建了多个线程,并将每个线程与 `threadFunction` 函数绑定。然后,我们使用 `join` 函数等待所有线程完成执行。
请注意,在创建线程时,我们使用了一个数组 `threads` 来存储线程对象。这是因为我们需要在后面的代码中对每个线程进行操作,例如等待线程完成。
c++循环创建多个线程
在C语言中,可以使用循环来创建多个线程。以下是一个简单的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM_THREADS 5
void *print_hello(void *thread_id) {
long tid = (long) thread_id;
printf("Hello from thread %ld\n", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for (t = 0; t < NUM_THREADS; t++) {
printf("Creating thread %ld\n", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void *) t);
if (rc) {
printf("Error: return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
pthread_exit(NULL);
}
```
该程序创建了5个线程,每个线程都会打印一条消息并退出。在循环中,通过调用pthread_create()函数来创建线程。该函数接受4个参数:指向线程标识符的指针、线程属性、指向函数的指针和传递给函数的参数。在这个例子中,我们传递了线程ID作为参数。然后,我们检查pthread_create()函数的返回值,以确保线程创建成功。
在主函数中,我们调用pthread_exit()来等待所有线程完成。