pthread_create
是 POSIX 线程(Pthreads)库中的一个函数,用于创建一个新的线程。这个函数允许程序在运行时并发执行多个线程,从而提高程序的效率和响应能力。
函数原型
#include <pthread.h>int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg);
参数说明
pthread_t *thread
: 指向pthread_t
类型的变量的指针,用于存储新创建线程的 ID。const pthread_attr_t *attr
: 指向线程属性对象的指针,可以为NULL
,表示使用默认属性。void *(*start_routine)(void *)
: 指向线程执行函数的指针,该函数的返回类型为void*
,参数类型为void*
。这是线程开始执行时调用的函数。void *arg
: 传递给start_routine
的参数,可以是任何类型的指针,通常用于传递数据给线程。
返回值
- 成功时,返回 0。
- 失败时,返回错误码,表示创建线程失败的原因。
示例代码
以下是一个简单的示例,展示如何使用 pthread_create
创建一个线程:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>// 线程执行的函数
void* thread_function(void* arg) {int *num = (int*)arg; // 将参数转换为整数指针printf("Thread %d is running\n", *num);return NULL;
}int main() {pthread_t thread1, thread2;int arg1 = 1, arg2 = 2;// 创建线程if (pthread_create(&thread1, NULL, thread_function, &arg1) != 0) {perror("Failed to create thread 1");return 1;}if (pthread_create(&thread2, NULL, thread_function, &arg2) != 0) {perror("Failed to create thread 2");return 1;}// 等待线程结束pthread_join(thread1, NULL);pthread_join(thread2, NULL);printf("Both threads have finished.\n");return 0;
}
代码解释
- 线程函数:
thread_function
是线程执行的函数,接收一个void*
类型的参数。在这个例子中,它将参数转换为整数并打印。 - 创建线程: 使用
pthread_create
创建两个线程,分别传递不同的参数。 - 等待线程结束: 使用
pthread_join
等待线程完成,确保主线程在子线程结束之前不会退出。 - 错误处理: 检查
pthread_create
的返回值,以确保线程成功创建。
注意事项
- 线程安全: 在多线程环境中,确保对共享资源的访问是线程安全的,通常使用互斥锁(mutex)来保护共享数据。
- 资源管理: 创建的线程在结束后需要被回收,使用
pthread_join
来避免资源泄漏。 - 属性设置: 可以通过
pthread_attr_init
和其他相关函数设置线程的属性,如栈大小、调度策略等。