phread_create函数的用法
时间: 2023-08-20 17:06:16 浏览: 45
pthread_create函数是POSIX线程库中的一个函数,用于创建一个新的线程。
函数原型如下:
```c
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
```
参数说明:
- thread:指向pthread_t类型的指针,用于存储新创建线程的ID。
- attr:指向pthread_attr_t类型的指针,用于设置新创建线程的属性,一般可以传入NULL,表示使用默认属性。
- start_routine:一个函数指针,指向新线程的入口函数,该函数将在新线程中执行。
- arg:传递给start_routine函数的参数。
函数返回值:
- 成功时,返回0,表示线程创建成功。
- 失败时,返回一个非零的错误码,表示线程创建失败。
例如,下面是一个使用pthread_create函数创建新线程的示例:
```c
#include <pthread.h>
#include <stdio.h>
void *thread_func(void *arg) {
int* num = (int*)arg;
printf("New thread created! Parameter: %d\n", *num);
pthread_exit(NULL);
}
int main() {
pthread_t thread_id;
int param = 10;
int ret = pthread_create(&thread_id, NULL, thread_func, ¶m);
if (ret != 0) {
printf("Failed to create thread!\n");
return 1;
}
printf("Main thread: New thread ID is %lu\n", thread_id);
pthread_join(thread_id, NULL); //等待新线程执行结束
printf("Main thread: New thread finished.\n");
return 0;
}
```
在上述示例中,我们定义了一个新线程的入口函数thread_func,用于在新线程中执行一些操作。然后,在主线程中调用pthread_create函数创建一个新线程,并传递参数param给新线程。最后,主线程使用pthread_join函数等待新线程执行结束。
希望以上信息能对你有所帮助!如果你还有其他问题,请继续提问。