#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define NUM_THREADS 5
void *print_hello(void *thread_id) {
long tid;
tid = (long)thread_id;
printf("Hello World! It's me, 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("In main: 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);
}
}
/* 等待所有线程完成 */
for (t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
printf("All threads completed. Exiting.\n");
pthread_exit(NULL);
}
#include <pthread.h> 引入了 POSIX 线程库的头文件,用于创建和管理线程。#define NUM_THREADS 5 定义了线程的数量为 5。void *print_hello(void *thread_id) 是每个线程执行的函数。它接收一个参数 thread_id 并打印一条消息。pthread_t threads[NUM_THREADS] 来存储线程 ID。for 循环创建多个线程,每个线程调用 print_hello 函数。pthread_create 的返回值,如果有错误则退出程序。pthread_join 等待所有线程完成。这个示例展示了如何在 Linux 下使用 POSIX 线程库创建和管理多线程程序。
上一篇:linux zip 压缩命令
下一篇:linux将文件夹权限给用户
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站