pthread_create() 是一个 POSIX 线程库函数,用于在创建一个新线程时使用。它的函数原型如下:
cpp
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine)(void*), void *arg);
pthread_create() 接受四个参数:
thread:指向 pthread_t 类型的指针,用于存储新线程的 ID。
attr:指向 pthread_attr_t 类型的指针,用于指定新线程的属性。如果传递 NULL,表示使用默认属性。
start_routine:是一个函数指针,指向新线程入口函数,该函数必须接受一个 void* 类型的参数,并返回一个 void* 类型的指针。
arg:是传递给 start_routine 的参数。
pthread_create() 函数用于创建一个新线程并运行指定的入口函数。新线程将在创建后开始执行,使用 start_routine 函数作为其执行起点。arg 参数可以被传递给 start_routine 函数作为其参数。
以下是一个简单的示例代码,演示了如何使用 pthread_create() 函数创建一个新线程:
cpp
#include <iostream>
#include <pthread.h>
void* threadFunction(void* arg) {
std::cout << "This is a new thread." << std::endl;
int value = *((int*)arg);
std::cout << "Received value in thread: " << value << std::endl;
pthread_exit(NULL);
}
int main() {
pthread_t thread;
int value = 42;
int result = pthread_create(&thread, NULL, &threadFunction, &value);
if (result == 0) {
std::cout << "Thread created successfully." << std::endl;
} else {
std::cerr << "Failed to create thread." << std::endl;
return 1;
}
pthread_join(thread, NULL);
std::cout << "Main thread exiting." << std::endl;
return 0;
}
在上述示例中,我们定义了一个名为 threadFunction 的函数作为新线程的入口函数。main 函数通过调用 pthread_create() 创建一个新线程,并将 threadFunction 作为新线程的入口函数。在 threadFunction 中,我们输出一条消息并打印传递给它的参数。
需要注意的是,通过 pthread_join() 函数,主线程将等待新线程执行完毕,确保所有线程都正确退出。 pthread_exit() 被用于在新线程中显式地终止线程的执行并退出。