linux-多线程设计pthread_create、…

创建线程:

# include <pthread.h>

int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn), void *arg)

tidp:创建线程时返回线程id

attr:线程属性(通常为空)

start_rtn:线程要执行的函数

arg:start_rtn的参数

返回值:创建成功就返回0,否则为非0;

 

编译

因为pthread的库不是linux系统的库,所以在进行编译的时候要加上

-lpthread

# gcc filename -lpthread

 

下面是一些例子:

1、thread_create.c

# include <stdio.h>
# include <pthread.h>

void *mythread1(void)
{
int i;
for(i=0; i<3; i++)
{
printf("this is the first pthread.\n");
sleep(1);
}
}

void *mythread2(void)
{
int i;
for(i=0; i<3; i++)
{
printf("this is the second pthread\n");
sleep(1);
}
}

int main(void)
{
int i = 0, ret = 0;
pthread_t id1, id2;

ret = pthread_create(&id1, NULL, (void *)mythread1, NULL);//创建线程1
if(ret)
{
printf("create pthread error\n");
return 1;
}

ret = pthread_create(&id2, NULL, (void *)mythread2, NULL);//创建线程2
if(ret)
{
printf("create pthread error\n");
return 1;
}

pthread_join(id1, NULL); //阻塞父进程,直到线程退出程序
pthread_join(id2, NULL);

return 0;
}

运行结果:

[regry@campusnetwork test]$ ./thread_create
this is the first pthread.
this is the second pthread
this is the first pthread.
this is the second pthread
this is the first pthread.
this is the second pthread


 

2、thread_int.c

# include <stdio.h>
# include <pthre

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值