循环创建多个子线程

测试源码

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <pthread.h>

void* myfunc(void* arg)
{
//    int num = *(int*)arg;
    int num = (int)arg;
    printf("%dth child pthread id: %lu\n", num, pthread_self());
    return NULL;
}

int main(int argc, const char* argv[])
{
    // 创建子线程
    pthread_t thid[5];
    // 返回错误号
    for(int i=0; i<5; ++i)
    {
  		  //int ret = pthread_create(&thid[i], NULL, myfunc, (void*)&i);
        int ret = pthread_create(&thid[i], NULL, myfunc, (void*)i);
        if(ret != 0)
        {
            printf("error number: %d\n", ret);
            // 根据错误号打印错误信息
            printf("error information: %s\n", strerror(ret));
        }
    }
    printf("parent pthread id: %lu\n", pthread_self());

    sleep(1);

    return 0;
}

测试结果

在这里插入图片描述

关键代码分析

//int ret = pthread_create(&thid[i], NULL, myfunc, (void*)&i);
int ret = pthread_create(&thid[i], NULL, myfunc, (void*)i);

线程函数指针传参,需要传的是一个一级指针,有时传递的是变量本身的值,有时候传递的是变量的地址。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值