Chinaunix首页 | 论坛 | 博客
  • 博客访问: 94759
  • 博文数量: 24
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 171
  • 用 户 组: 普通用户
  • 注册时间: 2014-10-24 12:12
个人简介

好好学习天天向上

文章分类

全部博文(24)

文章存档

2018年(1)

2016年(7)

2015年(6)

2014年(10)

我的朋友

分类: LINUX

2014-10-24 17:57:51

pthread_create和pthread_join使用例子,将下面的代码保存到thread.c中,

点击(此处)折叠或打开

  1. #include <pthread.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5.  void *thread_function(void *arg) {
  6.   int i;
  7.   for ( i=0; i<20; i++) {
  8.     printf("Thread says hi!\n");
  9.     sleep(1);
  10.   }
  11.   return NULL;
  12. }
  13. int main(void) {
  14.   pthread_t mythread;
  15.   
  16.   if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
  17.     printf("error creating thread.");
  18.     abort();
  19.   }
  20.   if ( pthread_join ( mythread, NULL ) ) {
  21.     printf("error joining thread.");
  22.     abort();
  23.   }
  24.   exit(0);
  25. }
gcc thread.c -o thread.o -pthread编译生成thread.o
[chenyun]$ gcc thread.c -o thread.o -pthread

执行thread.o:
[chenyun]$ ./thread.o
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
Thread says hi!
[chenyun]$


阅读(4943) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~