创建线程pthread_creat
时间: 2023-08-24 07:05:46 浏览: 104
要使用`pthread_create`函数创建线程,你需要包含`pthread.h`头文件,并按照以下方式调用该函数:
```c
#include <stdio.h>
#include <pthread.h>
void *thread_func(void *arg) {
// 线程执行的代码
printf("Hello from new thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int ret;
// 创建线程
ret = pthread_create(&thread, NULL, thread_func, NULL);
if (ret != 0) {
printf("Failed to create thread: %d\n", ret);
return 1;
}
// 等待线程结束
ret = pthread_join(thread, NULL);
if (ret != 0) {
printf("Failed to join thread: %d\n", ret);
return 1;
}
printf("Thread finished.\n");
return 0;
}
```
在上面的代码中,定义了一个新线程的入口函数`thread_func`。然后,在`main`函数中,使用`pthread_create`函数创建一个新线程,并将线程函数`thread_func`作为参数传递给它。`pthread_create`函数的第一个参数是一个指向线程标识符的指针,用于存储新线程的ID。第二个参数是线程属性,这里我们传递了NULL表示使用默认属性。第三个参数是线程函数的指针,最后一个参数是传递给线程函数的参数。
创建线程成功后,我们使用`pthread_join`函数等待新线程的结束。`pthread_join`函数的第一个参数是要等待的线程ID,第二个参数是指向线程返回值的指针,我们在这里传递了NULL,因为在`thread_func`中没有返回值。
最后,我们输出一条消息表示主线程的执行已经结束。
希望这个例子能帮助到你!如果还有其他问题,请随时提问。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.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)
![](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)