pthread_create 定值
时间: 2023-08-31 19:12:42 浏览: 108
pthread_create 函数是用于创建一个新的线程的函数。它的原型如下:
```c
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;如果发生错误,则返回对应的错误码。
注意:在使用 pthread_create 函数之前,需要在代码中包含 `<pthread.h>` 头文件,并链接 `-lpthread` 库。
例如,以下是创建一个新线程的简单示例:
```c
#include <stdio.h>
#include <pthread.h>
void* thread_func(void* arg) {
printf("Hello from the new thread!\n");
return NULL;
}
int main() {
pthread_t tid;
pthread_create(&tid, NULL, thread_func, NULL);
printf("Hello from the main thread!\n");
pthread_join(tid, NULL); // 等待新线程执行完毕
return 0;
}
```
这是一个简单的多线程程序,其中通过 pthread_create 函数创建了一个新线程,新线程执行 thread_func 函数,并在该函数中打印一条消息。同时,主线程在打印另一条消息后等待新线程执行完毕,然后程序结束。
阅读全文
相关推荐



















