Linux在主线程外开第二个线程c代码
时间: 2023-09-15 20:22:25 浏览: 49
下面是一个简单的示例代码,展示如何在 Linux 主线程外开启第二个线程。
```c
#include <stdio.h>
#include <pthread.h>
void* thread_function(void* arg)
{
printf("This is the second thread.\n");
return NULL;
}
int main()
{
pthread_t thread;
int result;
result = pthread_create(&thread, NULL, thread_function, NULL);
if (result != 0) {
perror("Thread creation failed");
return 1;
}
printf("This is the main thread.\n");
pthread_join(thread, NULL);
return 0;
}
```
在主函数中,我们创建了一个新的线程 `thread`,并将该线程的执行函数指定为 `thread_function`,同时传入一个参数 `NULL`。`pthread_create` 函数用于创建新线程,并将线程 ID(保存在 `thread` 变量中)返回。如果函数返回值不为 0,则表示创建线程失败。
在主函数中,我们输出了一行文字,表示这是主线程。然后,我们调用 `pthread_join` 函数等待线程 `thread` 的结束,并将其返回值忽略。
在新线程中,我们输出了一行文字,表示这是第二个线程。然后,我们返回 `NULL`,表示线程执行完毕。
要编译该程序,可以使用以下命令:
```
gcc -o program program.c -lpthread
```
其中,`-lpthread` 参数用于链接 pthread 库。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)