• 关于 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;
    }

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

  • 相关阅读:
    ASP.NET MVC之从控制器传递数据到视图
    ASP.NET MVC之从视图传递数据到控制器
    JQuery和ASP.NET之间的传值
    ASP.NET前台html页面AJAX提交数据后台ashx页面接收数据
    Variadic Templates 可变参数模板
    C++类型转换
    C++优化string,实现写时拷贝
    C++实现一个线程安全的单例模式
    C++ 实现简单的string
    C++实现简单的线程安全队列
  • 原文地址:https://www.cnblogs.com/superniaoren/p/3060802.html
Copyright © 2020-2023  润新知