pthread_create函数原型
时间: 2023-07-01 17:28:02 浏览: 45
pthread_create函数的原型为:
```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`:指向函数的指针,该函数将作为新线程的入口点。该函数必须接收一个void类型的指针参数并返回一个void类型的指针。
- `arg`:传递给start_routine函数的参数。
函数返回值为0表示成功,否则表示失败,返回错误码。
相关问题
Pthread_create函数
pthread_create函数是一个用于创建线程的函数,它属于POSIX线程库(pthread)的一部分。该函数的原型如下:
```c
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
```
该函数接受四个参数:
1. `thread`:指向pthread_t类型的指针,用于存储新创建线程的标识符。
2. `attr`:指向pthread_attr_t类型的指针,用于设置新线程的属性。可以传入NULL,表示使用默认属性。
3. `start_routine`:指向函数的指针,该函数是新线程要执行的函数。该函数必须具有以下形式:`void* function_name(void* arg)`,其中`arg`是传递给该函数的参数。
4. `arg`:传递给`start_routine`函数的参数。
当调用pthread_create函数时,它会创建一个新的线程,并将其加入到进程中。新线程会执行`start_routine`函数,并将`arg`作为参数传递给该函数。如果线程创建成功,pthread_create函数会返回0;否则,返回一个非零的错误码。
需要注意的是,新线程的执行顺序和主线程的执行顺序是不确定的,它们可能会并发执行。
Linux 的pthread_create函数
pthread_create函数是Linux下用于创建线程的函数。它的原型如下:
```c
#include <pthread.h>
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 <stdio.h>
#include <pthread.h>
void *thread_func(void *arg) {
int *num = (int *)arg;
printf("This is a new thread. The argument is %d\n", *num);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int num = 10;
int ret = pthread_create(&thread, NULL, thread_func, &num);
if (ret != 0) {
printf("Failed to create thread\n");
return 1;
}
printf("Main thread\n");
pthread_join(thread, NULL);
return 0;
}
```
该示例中,我们定义了一个新线程的起始函数thread_func,该函数接收一个整型参数,并在新线程中打印该参数的值。在主线程中,我们使用pthread_create函数创建了一个新线程,并将参数传递给新线程。然后,主线程继续执行自己的代码,最后使用pthread_join函数等待新线程的结束。