c语言多线程和信号量使用

线程使用:

int com_index=1;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;


int thread_run(void * ins){
    if (pthread_mutex_lock(&mutex)!=0){
        LOGI("***lock error");
        return -1;
    }
    const char *outs= static_cast<const char *>(ins);
    sleep(4);
    com_index+=1;
    LOGI("***run:%d---%s", com_index, outs);
    if (pthread_mutex_unlock(&mutex)!=0){
        LOGI("***unlock error");
        return -1;
    }
    return 0;
}

void thread_test(){
    // code start
    pthread_t  pthread;
    const char* ins="input args";
    int ret=pthread_create(&pthread, NULL, reinterpret_cast<void *(*)(void *)>(&thread_run), (void *) ins);
    if (ret!=0){
        LOGI("***init p error");
    }
    pthread_join(pthread, reinterpret_cast<void **>(&ret));
    LOGI("***fire end%d", ret);
}

信号量使用:

sem_t sem;

void thread_run2(void){
    sleep(3);
    sem_post(&sem);
}

void sem_test(){
    pthread_t  pthread;
    sem_init(&sem, 0, 0);
    LOGI("***fire start");
    int ret=pthread_create(&pthread, NULL, reinterpret_cast<void *(*)(void *)>(&thread_run2), NULL);
    if (ret!=0){
        LOGI("***init p error");
    }
    sem_wait(&sem);
    LOGI("***fire end%d", ret);
    sem_destroy(&sem);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值