线程的创建
#include <pthread.h>
int pthread_create(pthread_t *thread, const thread_attr_t *attr, void *(*routine)(void *), void *arg);
成功返回0,失败时返回错误码
thread 线程对象
attr 线程属性,NULL代表默认属性
routine 线程执行的函数
arg 传递给routine的参数 ,参数是void * ,注意传递参数格式,
编译错误分析:
1.
createP_t.c:14:36: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type [-Wincompatible-pointer-types]
ret = pthread_create(&tid,NULL,testThread,NULL);
In file included from createP_t.c:1:0:
/usr/include/pthread.h:233:12: note: expected ‘void * (*)(void *)’ but argument is of type ‘int * (*)(char *)’
意义:表示pthread_create参数3的定义和实际代码不符合,期望的是void * (*)(void *) ,实际的代码是int * (*)(char *)
解决方法:改为pthread_create(&tid,NULL,(void*)testThread,NULL);
2.
createP_t.c:(.text+0x4b):对‘pthread_create’未定义的引用
collect2: error: ld returned 1 exit status --------这个链接错误,
表示pthread_create这个函数没有实现
解决方法:编译时候加 -lpthread
注意事项:1. 主进程的退出,它创建的线程也会退出。
线程创建需要时间,如果主进程马上退出,那线程不能得到执行
所以会在主进程加入休眠1s
获取线程的id
通过pthread_create函数的第一个参数;
通过在线程里面调用pthread_self函数
地址传递:
- 通过地址传递参数,注意类型的转换
值传递:值传递,这时候编译器会告警,需要程序员自己保证数据长度正确
运行错误:
*** stack smashing detected ***: ./mthread_t terminated
已放弃 (核心已转储)
原因:栈被破坏了(数组越界)