关于 pthread_join的两个小例子

简单的例子是最好的学习方式:

example 1,从书上摘录的

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<string.h>

void *thr_fn1(void *arg){
        printf("thread 1 returning\n");
        return((void*)1);
}

void *thr_fn2(void *arg){
        printf("thread 2 exiting\n");
        pthread_exit((void*)2);
}
int main(){
        int err;
        pthread_t tid1,tid2;
        void *tret;
        err = pthread_create(&tid1,NULL,thr_fn1,NULL);
        if (err != 0)
                printf("can't create thread 1:%s\n",strerror(err));
        err = pthread_create(&tid2,NULL,thr_fn2,NULL);
        if (err != 0)
                printf("can't create thread 2:%s\n",strerror(err));

        err = pthread_join(tid1,&tret);
        if (err != 0)
                printf("can't join with thread 1:%s\n",strerror(err));
        printf("thread 1 exit code %d\n",(int)tret);

        err = pthread_join(tid2,&tret);
        if (err != 0)
                printf("can't join with thread 2:%s\n",strerror(err));
        printf("thread 2 exit code %d\n",(int)tret);
        exit(0);
}

example 2: 自己写的,刚接触pthread时写的,忘记了当初想验证什么,

#include <stdio.h>
#include <pthread.h>

const int thread_num = 4;
static int array[8];
void * print(void *arg){
//      int id = * (int *)arg;
        int id =  (int )arg;
        printf("thread %d it's sequn is %d\n", (int)pthread_self(), id);
        array[id] = id+100;
        return (void *)(&array[id]);
//      return (void *)(array[id]);
}
int main(int argc, char *argv[]){
        int i;
        pthread_t tid[thread_num];
        for(i=0; i<thread_num; i++){
                pthread_create(&tid[i], NULL, print, (void *)i);
        //      pthread_create(&tid[i], NULL, print, (void *)&i);
        }
        void *ret;
        for(i=0; i<thread_num; i++){
        //      pthread_join(tid[i], NULL);
                pthread_join(tid[i], &ret);
                printf("ret value = %d\n", *(int*)ret);
        //      printf("ret value = %d\n", (int)ret);
        }
        return 0;
}

给自己看的,做个纪念。。。

转载于:https://www.cnblogs.com/superniaoren/archive/2013/05/05/3060802.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值