linux c 线程变成,linux C线程的创建

这篇博客介绍了在Linux系统中如何使用pthread库创建和管理线程。通过pthread_create函数创建线程,并传递参数,然后使用pthread_join等待线程结束。示例代码展示了如何创建两个线程并执行不同的任务,每个线程打印特定的计数信息。
摘要由CSDN通过智能技术生成

pthread_create(pthread_t  handle, NULL, Thread_Main,   parameter)

需要引用 libpthread.so

函数简介

pthread_create是UNIX环境创建线程函数

头文件

#include

函数声明

int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *restrict_attr,void*(*start_rtn)(void*),void *restrict arg);

返回值

若成功则返回0,否则返回出错编号

参数

第一个参数为指向线程标识符的指针。

第二个参数用来设置线程属性。

第三个参数是线程运行函数的地址。

最后一个参数是运行函数的参数。

注意

在编译时注意加上-lpthread参数,以调用静态链接库。因为pthread并非Linux系统的默认库。

pthread_join函数

函数简介

函数pthread_join用来等待一个线程的结束。

函数原型为:

extern int pthread_join __P (pthread_t __th, void **__thread_return);

参数:

第一个参数为被等待的线程标识符

第二个参数为一个用户定义的指针,它可以用来存储被等待线程的返回值。

注意

这个函数是一个线程阻塞的函数,调用它的函数将一直等待到被等待的线程结束为止,当函数返回时,被等待线程的资源被收回。如果执行成功,将返回0,如果失败则返回一个错误号。

---------------------------------------------------------------

#include

#include

// linux API / pthread

#include

#include

struct ThreadParam

{

int id;

int max;

};

// 线程入口函数

void* Thread_Main(void* context)

{

ThreadParam* p = (ThreadParam*) context;

for(int i=0; imax; i++)

{

printf("thread: %d,  count: %d\n", p->id, i);

sleep(1);

}

free(p);

printf("thread : %d  exit . \n");

return NULL;

}

int main()

{

// 创建线程(同时启动线程)

pthread_t h1, h2;

// 创建第1个线程

ThreadParam* p1 = (ThreadParam*) malloc(sizeof(ThreadParam));

p1->id = 1;

p1->max = 10;

if(pthread_create(&h1, NULL, Thread_Main, p1) < 0)

{

printf("failed to create thread!\n");

return -1;

}

// 创建第2个线程

ThreadParam* p2 = (ThreadParam*) malloc(sizeof(ThreadParam));

p2->id = 2;

p2->max = 20;

if(pthread_create(&h2, NULL, Thread_Main, p2) < 0)

{

printf("failed to create thread!\n");

return -1;

}

pthread_join(h1, NULL);  //等待子线程结束;

pthread_join(h2, NULL);  //等待子线程结束;

printf("main exit.\n");

return 0;

}

编译:  g++ thread.cpp -lpthread-o thread

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值