pthread_create是C++中的一个函数,它用于创建一个新的线程。这个函数可以在不同的操作系统中使用,因为它是基于POSIX标准的。
函数原型如下:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(start_routine)(void), void *arg);
参数解释:
thread:指向线程标识符的指针,由函数返回。
attr:指向线程属性的指针,NULL表示使用默认属性。
start_routine:线程函数的指针,新线程会从这个函数开始执行。
arg:传递给线程函数的参数。
函数返回值:
成功返回0,否则返回错误代码。
示例代码:
#include <pthread.h>
#include <stdio.h>
void *print_message(void *arg) {
char *message = (char *)arg;
printf("%s\n", message);
pthread_exit(NULL);
}
int main() {
pthread_t thread;
char *message = "Hello, world!";
int rc = pthread_create(&thread, NULL, print_message, (void *)message);
if (rc) {
printf("Error: unable to create thread, %d\n", rc);
return -1;
}
pthread_join(thread, NULL);
return 0;
}
这个示例代码创建了一个新线程,执行print_message函数,打印出传递给它的字符串。pthread_create函数返回0表示线程创建成功,否则表示失败。在主线程中,我们调用pthread_join函数等待新线程执行完毕。
原文链接:https://blog.csdn.net/qq_51282224/article/details/129796185