zoukankan      html  css  js  c++  java
  • 关于 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;
    }

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

  • 相关阅读:
    学习笔记10-用户和组
    学习笔记9-环境变量
    学习笔记8-检测磁盘空间
    学习笔记7-监测程序
    学习笔记6-权限管理
    【数学】矩阵的逆
    【数学】矩阵
    【数学】Polya定理
    【图论】必经点和必经边
    【图论】点双连通分量
  • 原文地址:https://www.cnblogs.com/superniaoren/p/3060802.html
Copyright © 2011-2022 走看看