Chinaunix首页 | 论坛 | 博客
  • 博客访问: 417302
  • 博文数量: 54
  • 博客积分: 1186
  • 博客等级: 少尉
  • 技术积分: 668
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 04:57
文章分类

全部博文(54)

文章存档

2013年(1)

2012年(6)

2011年(47)

我的朋友

分类: LINUX

2012-05-30 19:12:47


点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <pthread.h>

  6. void *thread_function( void *arg );
  7. char message[] = "Hello World!\n";

  8. int main()
  9. {
  10.     int res;
  11.     pthread_t a_thread;
  12.     void *thread_result;

  13.     /* 创建线程 */
  14.     res = pthread_create( &a_thread, NULL, thread_function, ( void* )message );
  15.     if ( res != 0 )
  16.     {
  17.         perror( "Thread creation failed" );
  18.         exit( EXIT_FAILURE );
  19.     }

  20.     printf( "Waiting for thread to finish...\n" );
  21.     /* 等待线程结束 */
  22.     res = pthread_join( a_thread, &thread_result );

  23.     if ( res != 0 )
  24.     {
  25.         perror( "Thread join failed" );
  26.         exit( EXIT_FAILURE );
  27.     }

  28.     printf( "Thread joined, it returned %s\n", ( char* )thread_result );
  29.     printf( "Message is now %s\n", message );
  30.     exit( EXIT_SUCCESS );
  31. }

  32. void *thread_function( void *arg )
  33. {
  34.     printf( "thread_function is running. Argument was %s\n", ( char* )arg );
  35.     sleep( 3 );
  36.     strcpy( message, "Bye!" );
  37.     /* 线程返回值 */
  38.     pthread_exit( (void*)"Thank you for the CPU time" );
  39. }
主要涉及到3个函数:pthread_create, pthread_join, pthread_exit。

int
     pthread_create(pthread_t *thread, const pthread_attr_t *attr,
         void *(*start_routine)(void *), void *arg);

int
     pthread_join(pthread_t thread, void **value_ptr);

void
     pthread_exit(void *value_ptr);
阅读(1601) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~