pthread_create
函数是 POSIX 线程库(Pthreads)提供的函数之一,用于创建一个新的线程。它的原型如下:
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* start_routine(void*)
。arg
:是一个指向void
类型的指针,用于传递给start_routine
函数的参数。- 传递参数的功能很多开发者没有好好利用,而是选择了通过全局变量或其他形式传递
pthread_create
的作用是创建一个新的线程,并将执行流程从调用它的地方分离出去,使得新线程能够独立执行指定的 start_routine
函数。新线程开始执行后,它的执行将从 start_routine
函数的入口点开始。
下面是一个简单的示例,演示了 pthread_create
的基本用法:
#include <pthread.h>
#include <stdio.h>
// 线程执行的函数
void* thread_function(void* arg) {
printf("Hello from the new thread!\n");
return NULL;
}
int main() {
pthread_t tid; // 存储新线程的标识符
// 创建新线程
int result = pthread_create(&tid, NULL, thread_function, NULL);
if (result != 0) {
perror("pthread_create failed");
return -1;
}
// 主线程继续执行
printf("Hello from the main thread!\n");
// 等待新线程结束
result = pthread_join(tid, NULL);
if (result != 0) {
perror("pthread_join failed");
return -1;
}
return 0;
}
在这个例子中,pthread_create
创建了一个新线程,执行了 thread_function
函数。主线程继续执行并输出一行信息。随后,pthread_join
函数用于等待新线程的结束,确保在主线程结束之前新线程已经完成。
pthread_create
函数允许您通过其最后一个参数 arg
传递参数给新创建的线程。这个参数是一个指向 void
的指针,因此可以用来传递任何类型的数据。下面是一个示例,演示如何使用 pthread_create
传递参数给新线程:
#include <pthread.h>
#include <stdio.h>
// 结构定义,用于传递多个参数
struct ThreadArgs {
int arg1;
char arg2;
};
// 线程执行的函数
void* thread_function(void* arg) {
// 将传递的参数强制转换为结构体指针
struct ThreadArgs* args = (struct ThreadArgs*)arg;
// 在新线程中使用传递的参数
printf("Thread function received arguments: %d, %c\n", args->arg1, args->arg2);
return NULL;
}
int main() {
pthread_t tid; // 存储新线程的标识符
// 准备传递给新线程的参数
struct ThreadArgs args;
args.arg1 = 42;
args.arg2 = 'A';
// 创建新线程,并传递参数
int result = pthread_create(&tid, NULL, thread_function, (void*)&args);
if (result != 0) {
perror("pthread_create failed");
return -1;
}
// 主线程继续执行
printf("Hello from the main thread!\n");
// 等待新线程结束
result = pthread_join(tid, NULL);
if (result != 0) {
perror("pthread_join failed");
return -1;
}
return 0;
}
在这个例子中,定义了一个名为 ThreadArgs
的结构体,用于封装传递给新线程的参数。在 main
函数中,创建了一个 ThreadArgs
结构体对象,并设置了其中的字段。然后,通过 pthread_create
将新线程的执行函数设为 thread_function
,同时将 &args
传递给新线程作为参数。
在 thread_function
中,通过将 arg
强制转换为 ThreadArgs*
类型,可以得到传递的结构体参数,然后在新线程中使用这些参数。这样,就可以通过结构体传递多个参数给新线程。