#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
// 定义线程函数
void* thread_function(void* arg) {
int i;
for (i = 0; i < 5; i++) {
printf("Thread: %d\n", i);
sleep(1); // 模拟耗时操作
}
return NULL;
}
int main() {
pthread_t thread;
int ret;
// 创建线程
ret = pthread_create(&thread, NULL, thread_function, NULL);
if (ret != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
// 主线程继续执行
int i;
for (i = 0; i < 5; i++) {
printf("Main: %d\n", i);
sleep(1); // 模拟耗时操作
}
// 等待线程结束
pthread_join(thread, NULL);
printf("Thread completed.\n");
return 0;
}
包含头文件:
#include <pthread.h>
:用于线程相关的函数和数据类型。#include <stdio.h>
:用于标准输入输出函数。#include <stdlib.h>
:用于标准库函数,如 exit
。#include <unistd.h>
:用于 sleep
函数。定义线程函数:
void* thread_function(void* arg)
:这是线程的入口函数。它会打印一些信息并调用 sleep
来模拟耗时操作。创建线程:
pthread_create(&thread, NULL, thread_function, NULL)
:创建一个新的线程,并指定其入口函数为 thread_function
。主线程继续执行:
sleep
来模拟耗时操作。等待线程结束:
pthread_join(thread, NULL)
:主线程等待子线程结束。这确保了程序在所有线程完成后才退出。错误处理:
pthread_create
返回非零值,则表示创建线程失败,程序会输出错误信息并退出。上一篇:linux赋权限
下一篇:linux查找文件夹路径
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站