Linux C Phread 入门1---线程创建

首先,我的测试环境是Ubuntu12.04,用的eclispe cdt,当然,你有可以选择采用vim

今天主要讲的线程的创建。

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>//这个是pthread的头文件
void *print_message_function( void *ptr );//函数的预定义,参数类型是由pthread固定的,只能这样。
int main(int argc,char *argv[])
{
pthread_t thread1, thread2;//两个thread
const char *message1 = "Thread 1";
const char *message2 = "Thread 2";
int  iret1, iret2;
/* Create independent threads each of which will execute function */
iret1 = pthread_create( &thread1, NULL, print_message_function, (void*) message1);
iret2 = pthread_create( &thread2, NULL, print_message_function, (void*) message2);
/* Wait till threads are complete before main continues. Unless we  */
/* wait we run the risk of executing an exit which will terminate   */
/* the process and all threads before the threads have completed.   */
pthread_join( thread1, NULL);//join代表主线程等待thread1执行完,再往下走,和java中的join一样
pthread_join( thread2, NULL);
printf("Thread 1 returns: %d\n",iret1);
printf("Thread 2 returns: %d\n",iret2);
return 0;
}
void *print_message_function( void *ptr )
{
char *message;
message = (char *) ptr;
printf("%s \n", message);
return (void *)NULL;
}

关键点:

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

Arguments:

  • thread -返回新建的Thread ID . (unsigned long int defined in bits/pthreadtypes.h)

  • attr -一般设置为NULL,表示没有特殊的属性

  • void * (*start_routine) - 线程实际执行函数的函数指针..方法只有一个类型未void *的指针参数

  • *arg - pointer to argument of function. 想要传递多个参数,只能封装成struct后喂给这个函数


最后说下编译,最简单就是通过gcc命令行进行编译:

gcc -lpthread pthread1.c

Run: ./a.out

Results:


好了,这就是最基本的pthread线程创建过程,当然多线程最重要的还是线程之间的同步和数据交互,下回我再一一阐述。

如果有什么说的不正确的地方,还请各位看官指正。

转载于:https://my.oschina.net/hunterXue/blog/220197

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值