C++ 线程函数 pthread_create()

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值