pthread_create用法
时间: 2023-07-08 22:46:18 浏览: 183
pthread_create是一个 POSIX 线程库中的函数,用于创建一个新的线程。它的原型如下:
```c
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
```
参数说明:
- `thread`:指向 pthread_t 类型的指针,用于存储新线程的标识符。
- `attr`:指向 pthread_attr_t 类型的指针,用于设置新线程的属性,默认为 NULL。
- `start_routine`:一个函数指针,指向新线程将要执行的函数。
- `arg`:一个指向传递给新线程函数的参数的指针。
函数返回值:
- 成功:返回0
- 失败:返回错误码
示例代码:
```c
#include <stdio.h>
#include <pthread.h>
void *say_hello(void *arg) {
printf("Hello, %s!\n", (char *)arg);
pthread_exit(NULL);
}
int main() {
pthread_t tid;
char *name = "World";
if (pthread_create(&tid, NULL, say_hello, (void *)name) != 0) {
printf("Failed to create new thread!\n");
return 1;
}
pthread_join(tid, NULL);
return 0;
}
```
该程序会创建一个新线程,并在新线程中打印出 "Hello, World!" 的信息。在主线程中,我们使用 pthread_join 函数等待新线程执行完毕。
阅读全文
相关推荐
![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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)