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\n",tmp1);
  if (tmp1 !=0){
    printf("cannot join with thread1\n");
  }
  printf("thread1 end\n");


  tmp2=pthread_join(thread2,&retval);
  printf("thread2 return value(tmp) is %d\n",tmp2);
  if (tmp2 !=0){
    printf("cannot join with thread1\n");
  }
  printf("thread1 end\n");
}

char* print_hello(int num){
  printf("hello,word %d\n",num);
}

void create_result(int t_res){
  if(t_res !=0){
     printf("创建失败\n");
  }else{
     printf("创建成功\n");
  }
}

编译的时候会有搓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

 

posted @ 2014-04-15 10:13  墨迹哥's  阅读(165)  评论(0编辑  收藏  举报