linux编写父子线程
时间: 2024-01-23 17:05:50 浏览: 28
在Linux系统中,可以使用pthread库来编写父子线程。具体步骤如下:
1. 使用pthread_create函数创建子线程,该函数的参数为指向线程标识符的指针、线程属性以及线程运行的函数。
2. 在主线程中使用pthread_join函数等待子线程结束,该函数的参数为子线程标识符和一个指向线程返回值的指针。
3. 在子线程函数中实现需要执行的任务,并使用pthread_exit函数返回线程的返回值。
下面是一个简单的示例代码:
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void *child_thread(void *arg) {
printf("Child thread starts!\n");
sleep(2);
printf("Child thread ends!\n");
pthread_exit(NULL);
}
int main() {
pthread_t tid;
int ret;
printf("Parent thread starts!\n");
ret = pthread_create(&tid, NULL, child_thread, NULL);
if (ret != 0) {
printf("Error creating thread!\n");
return 1;
}
// 等待子线程结束
pthread_join(tid, NULL);
printf("Parent thread ends!\n");
return 0;
}
在这个例子中,主线程调用pthread_create函数创建子线程,子线程函数为child_thread。子线程在执行完任务后使用pthread_exit函数退出。主线程调用pthread_join函数等待子线程结束,然后程序结束运行。