linux 启动线程
时间: 2023-07-24 14:25:56 浏览: 51
在 Linux 中启动线程可以使用 pthread 库。以下是一个基本的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread_func(void *arg) {
printf("Thread function is running\n");
pthread_exit(NULL);
}
int main() {
pthread_t tid;
int ret;
ret = pthread_create(&tid, NULL, thread_func, NULL);
if (ret != 0) {
printf("Error: pthread_create() failed\n");
exit(EXIT_FAILURE);
}
printf("Main function after pthread_create()\n");
pthread_join(tid, NULL);
return 0;
}
```
在此示例中,我们创建了一个名为 `thread_func` 的线程函数,并在 `main` 函数中使用 `pthread_create` 函数创建一个新线程。`pthread_create` 函数的第一个参数是指向线程标识符的指针,第二个参数是线程属性,第三个参数是指向线程函数的指针,最后一个参数是传递给线程函数的参数。
在此示例中,我们将第二个和第四个参数设置为 `NULL`,表示默认线程属性和不传递参数给线程函数。如果 `pthread_create` 函数成功创建线程,则返回值为 0。
然后,我们在主函数中打印一条消息,并使用 `pthread_join` 函数等待线程结束。最后,我们在 `main` 函数中返回 0。
编译并运行此代码,将会看到如下输出:
```
Main function after pthread_create()
Thread function is running
```
这说明新线程已经启动并开始执行 `thread_func` 函数。