酷代码 AI
菜单
服务商

启动线程 (&获取C语言格式基址, , C线程)写一个10多线程

以下是一个使用C语言创建10个线程的示例代码,每个线程的任务是打印自身的线程ID和一个表示线程序号的参数。代码中会涉及到线程的创建、等待等操作,使用了POSIX线程库(pthread)。 ```c #include <stdio.h> #include <pthread.h> // 线程的执行函数 void *thread_function(void *arg) { // 将传入的参数转换为整数类型 int thread_num = *(int *)arg; // 打印线程的序号和线程ID printf("Thread %d with ID %lu is running.\n", thread_num, pthread_self()); // 线程执行完毕,返回NULL return NULL; } int main() { // 定义线程数组,用于存储10个线程的ID pthread_t threads[10]; // 定义一个整数数组,用于存储每个线程的序号 int thread_args[10]; // 创建10个线程 for (int i = 0; i < 10; i++) { // 存储当前线程的序号 thread_args[i] = i; // 创建线程,传入线程ID指针、线程属性(这里使用默认属性)、线程执行函数和参数 if (pthread_create(&threads[i], NULL, thread_function, &thread_args[i]) != 0) { // 如果线程创建失败,打印错误信息并退出程序 perror("pthread_create"); return 1; } } // 等待所有线程执行完毕 for (int i = 0; i < 10; i++) { // 等待指定线程结束,传入线程ID和用于存储线程返回值的指针(这里不关心返回值,传入NULL) if (pthread_join(threads[i], NULL) != 0) { // 如果等待线程结束失败,打印错误信息并退出程序 perror("pthread_join"); return 1; } } // 所有线程执行完毕,打印提示信息 printf("All threads have completed.\n"); return 0; } ``` 代码说明: 1. `thread_function` 函数:这是每个线程的执行函数,它接受一个 `void *` 类型的参数,将其转换为 `int` 类型,然后打印线程的序号和线程ID。 2. `main` 函数: - 定义了一个 `pthread_t` 类型的数组 `threads` 用于存储10个线程的ID,以及一个 `int` 类型的数组 `thread_args` 用于存储每个线程的序号。 - 使用 `for` 循环创建10个线程,每个线程的执行函数为 `thread_function`,并传入对应的线程序号作为参数。 - 使用另一个 `for` 循环等待所有线程执行完毕,使用 `pthread_join` 函数确保主线程在所有子线程结束后才继续执行。 3. 编译和运行: - 由于使用了POSIX线程库,编译时需要链接 `pthread` 库,命令如下: ```sh gcc -o multi_thread multi_thread.c -pthread ``` - 运行编译后的可执行文件: ```sh ./multi_thread ``` 注意事项: - 代码中的线程执行函数只是简单地打印信息,你可以根据实际需求修改该函数的功能。 - 线程创建和等待过程中可能会出现错误,使用 `perror` 函数打印错误信息。 [2025-11-28 03:15:06 | AI问答 | 810点数解答]

相关提问
发财导航,免费问AI
实用工具查看更多