免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1390 | 回复: 2
打印 上一主题 下一主题

[Linux] Linux下一个简单的线程示例程序 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2013-04-14 21:23 |只看该作者 |倒序浏览
  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);

论坛徽章:
23
双鱼座
日期:2013-08-30 09:25:19辰龙
日期:2014-07-28 11:22:24白羊座
日期:2014-08-26 10:34:1815-16赛季CBA联赛之浙江
日期:2016-03-15 10:51:5415-16赛季CBA联赛之八一
日期:2016-05-31 09:38:3615-16赛季CBA联赛之辽宁
日期:2017-08-31 14:59:2115-16赛季CBA联赛之辽宁
日期:2017-12-06 14:12:3615-16赛季CBA联赛之天津
日期:2019-01-02 15:25:4915-16赛季CBA联赛之深圳
日期:2020-12-06 11:26:21狮子座
日期:2014-05-19 09:16:35技术图书徽章
日期:2014-03-27 13:37:39技术图书徽章
日期:2013-08-30 09:28:52
2 [报告]
发表于 2013-04-16 15:31 |只看该作者
支持下。

线程参数用全局变量啊,,

楼主普及下线程传递参数的方式呗,整型、字符串、结构体等

论坛徽章:
0
3 [报告]
发表于 2013-04-16 17:27 |只看该作者
线程传递的参数是 void型的  换种意义说就是你想让它是什么型就是什么型
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP