#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// 定义线程函数
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[5];
int rc;
long t;
// 创建5个线程
for (t = 0; t < 5; 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 < 5; t++) {
pthread_join(threads[t], NULL);
}
printf("All threads completed\n");
pthread_exit(NULL);
}
包含头文件:
#include <pthread.h>:引入POSIX线程库的头文件。#include <stdio.h>:用于标准输入输出函数。#include <stdlib.h>:用于标准库函数,如exit()。#include <unistd.h>:用于Unix系统调用。定义线程函数:
void* print_hello(void* thread_id):这是每个线程执行的函数。它接收一个参数thread_id,并打印一条消息。主函数:
pthread_t threads[5]:定义一个数组来存储5个线程的标识符。for循环创建5个线程,每个线程都执行print_hello函数,并传递一个唯一的线程ID。pthread_create函数创建线程,并检查返回值以确保线程创建成功。pthread_join函数等待所有线程完成。结束程序:
这段代码展示了如何在Linux下使用POSIX线程库创建和管理多个线程。
上一篇:linux测试磁盘读写速度
下一篇:linux查看内存条信息
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站