zoukankan      html  css  js  c++  java
  • C 多线程学习

    一直都觉得多线程啥的是个比较麻烦的东西,今天好好看了下,写了个DEMO出来。

    看看怎么灵活运用,估计还得再多写写,回头改造下之前那个例子。

    #include<pthread.h>
    #include<stdio.h>
    
    char* print_hello(int num);
    void create_result(int t_res);
    
    void main(){
      int tmp1,tmp2;
      void *retval;
      pthread_t thread1,thread2;
      int res_thred1,res_thred2;
    
      //创建线程,判断是否成功
      create_result(pthread_create(&thread1,NULL,(void *)&print_hello,(void *) 1));
      create_result(pthread_create(&thread2,NULL,(void *)&print_hello,(void *) 2));
    
      //join掉线程并返回结果
      tmp1=pthread_join(thread1,&retval);
      printf("thread2 return value(tmp) is %d
    ",tmp1);
      if (tmp1 !=0){
        printf("cannot join with thread1
    ");
      }
      printf("thread1 end
    ");
    
    
      tmp2=pthread_join(thread2,&retval);
      printf("thread2 return value(tmp) is %d
    ",tmp2);
      if (tmp2 !=0){
        printf("cannot join with thread1
    ");
      }
      printf("thread1 end
    ");
    }
    
    char* print_hello(int num){
      printf("hello,word %d
    ",num);
    }
    
    void create_result(int t_res){
      if(t_res !=0){
         printf("创建失败
    ");
      }else{
         printf("创建成功
    ");
      }
    }

    编译的时候会有搓B问题,gg之。

    undefined reference to 'pthread_create'
    undefined reference to 'pthread_join'

    该问题原因:pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库

    解决方法:

      gcc thread.c -o thread -lpthread
  • 相关阅读:
    PAT-乙级-1011. A+B和C (15)
    PAT-乙级-1010. 一元多项式求导 (25)
    PAT-乙级-1009. *说反话 (20)
    PAT-乙级-1008. 数组元素循环右移问题 (20)
    PAT-乙级-1007. 素数对猜想 (20)
    PAT-乙级-1006. 换个格式输出整数 (15)
    PAT-乙级-1005. 继续(3n+1)猜想 (25)
    PAT-乙级-1004. 成绩排名 (20)
    BZOJ 1030: [JSOI2007]文本生成器
    BZOJ 2938: [Poi2000]病毒
  • 原文地址:https://www.cnblogs.com/xiaoCon/p/3665603.html
Copyright © 2011-2022 走看看