pthread_create
是Linux操作系统中用于创建新线程的函数
#include#include #include // 定义一个将要在线程中执行的功能 void *print_hello(void *arg) { char *name = (char *)arg; printf("Hello, %s!\n", name); pthread_exit(NULL); } int main() { pthread_t thread_id; // 用于存储线程ID的变量 char *thread_name = "Thread-1"; // 定义线程名 // 使用pthread_create创建新线程 int result = pthread_create(&thread_id, NULL, print_hello, (void *)thread_name); if (result != 0) { printf("Error: unable to create thread\n"); exit(1); } // 在线程执行完成后,回收资源 pthread_join(thread_id, NULL); printf("Main thread exits.\n"); return 0; }
在这个示例中,我们首先包含了pthread.h
头文件,然后定义了一个名为print_hello
的函数,该函数将作为线程的执行功能。我们在线程中打印一条包含线程名的问候信息,然后使用pthread_exit
函数结束线程。
在main
函数中,我们创建了一个pthread_t
类型的变量thread_id
来存储线程ID。我们还定义了一个字符串thread_name
,用于在线程中显示。接下来,我们调用pthread_create
函数来创建新线程,并将thread_id
、NULL
(表示使用默认属性)、print_hello
函数指针和thread_name
作为参数传递给它。如果线程创建成功,pthread_create
将返回0,否则返回一个非零错误代码。
在线程执行完成后,我们使用pthread_join
函数等待线程结束并回收资源。最后,主线程打印一条退出信息并返回0。