#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;
int i;
// 创建多个线程
for (i = 0; i < 5; i++) {
printf("In main: creating thread %d\n", i);
rc = pthread_create(&threads[i], NULL, print_hello, (void*)i);
if (rc) {
printf("ERROR; return code from pthread_create() is %d\n", rc);
exit(-1);
}
}
// 等待所有线程完成
for (i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
printf("All threads completed.\n");
pthread_exit(NULL);
}
包含头文件:
#include <pthread.h>
:用于多线程编程。#include <stdio.h>
和 #include <stdlib.h>
:用于标准输入输出和内存管理。#include <unistd.h>
:用于一些系统调用。定义线程函数:
void* print_hello(void* thread_id)
:这是每个线程执行的函数,它接收一个参数(线程ID),并打印一条消息。主函数:
pthread_t threads[5]
。pthread_create
函数创建线程,并传递线程ID作为参数。pthread_join
函数等待所有线程完成。pthread_exit
终止主线程。错误处理:
pthread_create
返回非零值,则表示创建线程失败,程序会打印错误信息并退出。这段代码展示了如何在Linux环境下使用POSIX线程库(pthread)创建和管理多个线程。
上一篇:linux who
下一篇:linux tar压缩文件夹
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站