使用C++通过调用 API 函数创建多个线程,输 出每个线程的标识,然后结束这几个线程。 在一个进程中创建 3 个线程,名字分别为 threada、threadb、threadc。 threada 输出“hello world! ”。 threadb 输出“My name is …”。 threadc 输出“Please wait…”,然后 sleep 5 秒钟,接着输出“I wake up”。
时间: 2023-06-09 18:06:34 浏览: 102
好的,以下是您的问题的答案:
首先,通过调用API函数,我们可以使用pthread_create来创建线程,并使用pthread_join来等待线程完成并回收其资源。要创建多个线程并输出其标识符,我们可以在主线程中使用一个循环来迭代每个线程,如下所示:
```
#include <stdio.h>
#include <pthread.h>
void* thread_a(void* arg) {
printf("Hello world!\n");
pthread_exit(NULL);
}
void* thread_b(void* arg) {
printf("My name is...\n");
pthread_exit(NULL);
}
void* thread_c(void* arg) {
printf("Please wait...\n");
sleep(5);
printf("I wake up!\n");
pthread_exit(NULL);
}
int main() {
pthread_t threads[3];
int i;
// 创建线程并输出其标识符
for (i = 0; i < 3; i++) {
if (i == 0) {
pthread_create(&threads[i], NULL, thread_a, NULL);
} else if (i == 1) {
pthread_create(&threads[i], NULL, thread_b, NULL);
} else {
pthread_create(&threads[i], NULL, thread_c, NULL);
}
printf("Created thread %d with id %lu\n", i, threads[i]);
}
// 等待线程完成并回收其资源
for (i = 0; i < 3; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
```
在这个程序中,我们定义了三个线程函数thread_a,thread_b和thread_c,它们分别打印不同的消息,并在完成后通过pthread_exit退出线程。 在主函数中,我们创建了一个包含三个元素的线程数组,并通过循环调用pthread_create来创建每个线程,并在每个线程创建时打印其标识符。 接下来,我们使用另一个循环来等待每个线程完成,并使用pthread_join回收其资源。最后,我们返回0以指示程序正常退出。
希望这个答案可以回答您的第一个问题,如有其他疑问,请随时问我!