Linux 应用pthread_create函数,启动一个线程,在线程中执行一个循环输出,在主进程中执行一个较长时间执行的任务。
时间: 2024-02-18 22:05:41 浏览: 27
好的,以下是一个简单的 C 代码示例,用于在 Linux 环境下使用 pthread_create 函数启动一个线程,在线程中执行一个循环输出,在主进程中执行一个较长时间执行的任务:
```c
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
void *thread_func(void *arg) {
// 在线程中执行循环输出
for (int i = 0; i < 10; i++) {
printf("Thread output %d\n", i);
sleep(1);
}
return NULL;
}
int main() {
pthread_t tid;
int ret;
// 创建线程
ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
printf("Thread creation failed\n");
return 1;
}
// 在主进程中执行较长时间执行的任务
for (int i = 0; i < 5; i++) {
printf("Main task %d\n", i);
sleep(2);
}
// 等待线程结束
pthread_join(tid, NULL);
return 0;
}
```
在上面的代码中,我们定义了一个函数 `thread_func`,用于在线程中执行循环输出。然后在 `main` 函数中,我们先使用 `pthread_create` 函数创建一个线程,并且将 `thread_func` 函数作为线程的入口函数。接着在主进程中,我们执行一个较长时间的任务,这里我们只是简单地循环输出一些信息。最后调用 `pthread_join` 函数等待线程结束。注意,在主进程中调用 `pthread_join` 函数是为了等待线程结束,防止线程在主进程结束之前被强制终止。