linux下开启线程
时间: 2023-07-26 08:10:54 浏览: 115
在Linux下,可以使用pthread库来开启线程。具体步骤如下:
1. 包含头文件pthread.h。
2. 定义一个函数,作为新线程的入口点。
3. 在主线程中调用pthread_create函数来创建新线程,该函数的参数包括指向线程标识符的指针、线程属性以及新线程的入口点函数。
以下是一个简单的示例代码:
```
#include <pthread.h>
#include <stdio.h>
void *thread_func(void *arg) {
printf("This is a new thread.\n");
return 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");
return 1;
}
printf("Main thread: Created new thread (%lu)\n", tid);
pthread_exit(NULL);
return 0;
}
```
在上面的代码中,我们定义了一个名为thread_func的函数,作为新线程的入口点。在主线程中,我们调用pthread_create函数来创建新线程,该函数的第一个参数是指向线程标识符的指针,第二个参数是线程属性,可以为NULL表示使用默认属性,第三个参数是新线程的入口点函数,最后一个参数是传递给新线程的参数。如果pthread_create函数成功创建新线程,则返回0,否则返回一个错误码。
在上面的示例代码中,当新线程执行完毕后,我们并没有调用pthread_join函数来等待新线程结束并回收其资源,而是直接调用了pthread_exit函数来退出主线程。这是因为我们只是演示了如何创建新线程,并没有在新线程中做任何有意义的工作。在实际使用中,我们需要根据需求在新线程中执行一些任务,并在新线程结束后使用pthread_join函数来等待其结束并回收资源。