c语言 使用多线程

头文件

#include<pthread.h>

函数声明

1

2

int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,

void *(*start_rtn)(void*),void *arg);

返回值

若线程创建成功,则返回0。若线程创建失败,则返回出错编号,并且*thread中的内容是未定义的。

返回成功时,由tidp指向的内存单元被设置为新创建线程的线程ID。attr参数用于指定各种不同的线程属性。新创建的线程从start_rtn函数的地址开始运行,该函数只有一个万能指针参数arg,如果需要向start_rtn函数传递的参数不止一个,那么需要把这些参数放到一个结构中,然后把这个结构的地址作为arg的参数传入。

参数

第一个参数为指向线程标识符指针

第二个参数用来设置线程属性。

第三个参数是线程运行函数的起始地址。

最后一个参数是运行函数的参数。

传参数

1.传多个参数:封装成结构体

typedef struct args{
    int id;
    char * name;
} ARGS;
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
#include "log.h"
#include "test.h"

int * thread(void * arg)
{
    pthread_t newthid;
    ARGS *args = (ARGS *)arg;
    newthid = pthread_self();
    LOGI(LOG_TAG,"this is a new thread, args->id = %d\n", args->id);
    LOGI(LOG_TAG,"this is a new thread, args->name = %s\n", args->name);
    return 0;
}

int main(void)
{
    pthread_t thid;

    LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());
    ARGS *args;
    args->id = 10;
    args->name ="test";
    //int j=10;
    if(pthread_create(&thid, NULL, thread, args) != 0) {
        LOGI(LOG_TAG,"thread creation failed\n");
    }
}
I/jniTest: this is a new thread, args->id = 10
I/jniTest: this is a new thread, args->name = test

2.传单个参数

int * thread(void * arg)
{
    pthread_t newthid;

    newthid = pthread_self();
    int j = (int *)arg;
    LOGI(LOG_TAG,"this is a new thread, j = %d\n", j);
    return 0;
}

int main(void)
{
    pthread_t thid;

    LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());

    int j=10;
    if(pthread_create(&thid, NULL, thread, j) != 0) {
        LOGI(LOG_TAG,"thread creation failed\n");
    }
}
int * thread(void * arg)
{
    pthread_t newthid;

    newthid = pthread_self();
    char* j = (char *)arg;
    LOGI(LOG_TAG,"this is a new thread, j = %s\n", j);
    return 0;
}

int main(void)
{
    pthread_t thid;

    LOGI(LOG_TAG,"main thread ,ID is %ld\n",pthread_self());

    char *j="10";
    if(pthread_create(&thid, NULL, thread, j) != 0) {
        LOGI(LOG_TAG,"thread creation failed\n");
    }
}

3.不传参数

pthread_create(&thid, NULL, thread, NULL)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xiaowang_lj

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值