linux 创建线程函数吗,Linux多线程——线程创建

线程pthread_create创建线程函数。函数声明:int pthread_create(pthread_t *restrict tidp,const pthread_attr_t *pth_attr,void*(*start_rtn)(void*),void *arg);

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

参数说明:

tid:指向所创建的线程ID的指针。

pth_attr:用于设置线程属性,通常为空。

start_rtn:线程运行函数的地址,函数指针类型。

arg:传给线程的参数,运行函数的参数,即传给start_rtn的参数。

样例:创建线程,在线程中进行运行大数乘法。使用code::blocks,Ubantu 18.04注意:编译程序需要使用pthread库(pthread库不是默认库),在编译时加上-lpthread(在终端下)或者在code::blocks里选择Project -> Build options -> Linker settings -> Link libraries 里加上-pthread以避免出现错误undefined reference to 'pthread_create'。

4766194d089dda4a6bd78239bd23ff88.png添加pthread库支持

#include

#include

#include

#include

#include

void *create(void *message){

int num_1[5]={1,2,3,4,5},num_2[5]={6,7,8,9,9};

int size=10;

int result[size]={0};

int i=0;

for(i=0;i<5;i++){

int k=i;

for(int j=0;j<5;j++)

result[k++]+=num_1[i]*num_2[j];

}

for(i=0;i

if(result[i]>=10){

result[i+1]+=result[i]/10;

result[i]%=10;

}

}

printf("multiply end:result->\n");

for(int n=10;n>0;n--)

printf("%d",result[n-1]);

getchar();

return (void*)result;

}

int main(int argc,char*argv[]){

pthread_t threadId;

int error;

int num[10]={0};

error=pthread_create(&threadId,NULL,create,(void*)num);

if(error!=0){

printf("thread create error\n");

return -1;

}

pthread_join(threadId,NULL);

return 0;

}

运行结果:54321*99876->5425364196

a1cbc99d89961a4585d3371369fbf9cf.png相乘结果:5425364196

调试:

ac5f00fdabba14281675c0fe38d495c1.png调试变量监测:相乘结果result数组

在调试时出现warning: GDB: Failed to set controlling terminal: Operation not permitted

可以不用管,要看哪步的结果添加断点即可。

66274bf9f0e0f774e5efd15cf52ec878.png线程相关概念

基本概念 线程创建 线程挂起 线程终止 互斥和同步

举报/反馈

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值