pthread_create函数头文件(pthread_create函数用法)

http://www.itjxue.com  2023-02-21 10:37  来源:未知  点击次数: 

c语言怎么创建线程和使用

1、添加线程相关的头文件:#includepthread.h

2、线程创建函数是pthread_create()函数,该函数的原型为:

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

3、线程退出函数是pthread_exit()函数,该函数的原型为:

void?pthread_exit(void?*retval);

创建线程的示例程序如下:

/*

**程序说明:创建线程函数pthread_create()函数的使用。

*/

#include?stdio.h

#include?pthread.h

#include?unistd.h

#include?stdlib.h

#include?string.h

//打印标识符的函数

void?print_ids(const?char?*str)

{

pid_t?pid; //进程标识符

pthread_t?tid; //线程标识符

pid=getpid(); //获得进程号

tid=pthread_self(); //获得线程号

printf("%s?pid:%u?tid:%u?(0x%x)\n",

str,(unsigned?int)pid,(unsigned?int)tid,(unsigned?int)tid);?//打印进程号和线程号

}

//线程函数

void*?pthread_func(void?*arg)

{

print_ids("new?thread:"); //打印新建线程号

return?((void*)0);

}

//主函数

int?main()

{

int?err;

pthread_t?ntid; //线程号

err=pthread_create(ntid,NULL,pthread_func,NULL); //创建一个线程

if(err?!=?0)

{

printf("create?thread?failed:%s\n",strerror(err));

exit(-1);

}

print_ids("main?thread:"); //打印主线程号

sleep(2);

return?0;

}

linux里面线程编译运行问题

gcc xxx.c -lpthread 其中的-l是指包含的lib库,具体写法可以man gcc看下

多线程函数除了要包含头文件pthread.h外还必须要包含lib库pthread

pthread_create是创建线程,但具体的线程里面做什么事是在void *create(void *arg)里,这个函数名是自己任意区的,但返回值和参数一般都是void*类型,因为pthread_create函数的定义就是这样

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

linux pthread_create() 产生斐波那契数列

1. pthread_join 是阻塞函数,运行该函数后主线程会阻塞等待子线程操作结束,你把pthread_join放在主线程输出之后,存在这样的问题:在子线程还没赋值完成前,父线程已经把未操作的值输出了。

2.传递参数错误,pthread_create传递的是"a",也就是数组的起始地址的地址,你只是改变数组值,不需要对起始地址更改,完全可以传递 a,而且看你thread_fun函数应该传递的是a。

3. 最关键的,我纳闷怎么没输出,检查了下你的thread_fun才发现“for(k=2;k=512;k++)”,数组越界了! 造成的结果是把n值直接给改了。。

修改版 (有warning, 最好把参数设成void *):

#include stdio.h

#include string.h

#include stdlib.h

#include pthread.h /*pthread_create()......*/

#include unistd.h

pthread_t ntid;

void *thread_fun(int *p) {/*.......*/

int k;

p[0] = 0;

p[1] = 1;

for(k=2;k512;k++)

{

p[k] = p[k-1] + p[k-2];

}

return NULL;

}

int main(void){

int err;

int i,n;

int a[512];

printf("Please enter n:(n=3 n=512) ");

scanf("%d",n);

/*........*/

err=pthread_create(ntid,NULL,thread_fun,(void *)a);

if (err!=0) {

fprintf(stderr, "......: %s\n", strerror(err));

exit(1);

}

pthread_join(ntid,NULL); /*...1.....*/

for(i = 0 ; i=n ; i++){

printf("F[%d] = %d\n",i,a[i]);

}

}

`pthread_create' 问题,请问下面这个报错怎么搞啊

pthread_create是UNIX环境创建线程函数;

1、头文件#includepthread.h;

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

(责任编辑:IT教学网)

更多

推荐浏览器文章