详细解读函数pthread_create
函数pthread_create是POSIX线程库中的一种函数,用于创建一个新的线程。
函数原型如下:
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:指向函数指针,该函数将作为新线程的入口函数。新线程将从该函数开始执行。
- arg:传递给start_routine函数的参数。
返回值:
- 成功创建线程时,返回0;
- 创建线程失败时,返回非零错误码。
函数功能:
- 创建一个新线程,并将其加入到进程中运行;
- 利用start_routine函数作为新线程的入口函数;
- 可以通过attr参数设置新线程的属性,如线程栈大小、调度策略等。
使用示例:
#include <stdio.h>
#include <pthread.h>
void* print_message(void *ptr) {
char *message = (char *)ptr;
printf("%s\n", message);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
char *message = "Hello, world!";
int result = pthread_create(&thread, NULL, print_message, (void *)message);
if (result != 0) {
printf("Error creating thread: %d\n", result);
return 1;
}
pthread_join(thread, NULL);
return 0;
}
该示例中,使用pthread_create函数创建了一个新线程,并将print_message函数作为新线程的入口函数。print_message函数接收一个指针参数,用于打印传入的消息。在主线程中,调用pthread_join函数等待新线程结束,然后程序退出
原文地址: http://www.cveoy.top/t/topic/iRxB 著作权归作者所有。请勿转载和采集!