函数 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 函数等待新线程结束,然后程序退出。

C语言 pthread_create 函数详解 - 创建新线程

原文地址: https://www.cveoy.top/t/topic/qxwE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录