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
  • 相关阅读:
    [题解] [NOIP2008] 双栈排序——关系的冲突至图论解法
    [搬运] [贪心]NOIP2011 观光公交
    [总结] 最短路径数问题
    [持续更新]一些zyys的题的集合
    [教程]Ubuntu下完整配置自动壁纸切换
    在NOILINUX下的简易VIM配置
    [模板]ST表浅析
    21、Android--RecyclerView
    20、Android--GridView
    19、Android--ListView
  • 原文地址:https://www.cnblogs.com/xiaoCon/p/3665603.html
Copyright © 2011-2022 走看看