1
创建线程:
#inclued<pthread.h>
int pthread_create(pthread_t*tidp,const pthread_attr_t*attr,void*(*start_rtn)(void),void*arg)
tidp:线程id
attr:线程属性(通常为空)
start_rtn:线程要执行的函数
arg:start_rtn的参数
2
编译--因为pthread的库不是linux系统的库,所以在进行编译的时候要加上
-lpthread
#gcc filename -lpthread
实例分析
thread_create.c
thread_int.c
thread_string.c
thread_struct.c
thread_share.c
实例分析
【1】create.c
ret = pthread_create(&id1, NULL, (void*)myThread1, NULL);
成功创建线程,会自动把线程号给id1赋值
第三个参数,是线程要执行的函数
第四个是执行函数的参数,没有
【2】int.c//传递整型,其类同于传递字符串、结构体
int test=4;
int *attr=&test;
error=pthread_create(&tidp,NULL,create,(void *)attr);
为什么做个转化,因为void *create(void *arg)函数的参数是指在形式的。
【3】share.c共享数据段
注意:
【1】共享数据段
【2】当数据段和栈里都有a的赋值,那就有了优先级
【3】当int a=1;被注释掉,那程序就出错,因为线程里的a未被定义。
【4】static int a=4;
【1】
[root@embedclub test1]# ./thread_share
a = 1
new pthread ...
a=1
in main 2: a = 2
new thread is created ...
所以会出现a=2
【2】
int a = 1;//在数据段里
int main(int argc,char *argv[])
{
pthread_t tidp;
int error;
int a=5;//在堆里面
【4】
[root@embedclub test1]# ./thread_share
a = 5
new pthread ...
a=4
in main 2: a = 5
new thread is created ...
//线程和进程是共享数据段
3
终止线程
任何一个线程中调用exit或_exit,那么整个进程都会终止。
线程正常退出方式有:
【1】线程从启动例程中返回
【2】线程可以被另一个进程终止
【3】现在自己调用pthread_exit函数
4
线程退出:pthread_exit函数
#inclued<pthread.h>
void pthread_exit(void*rval_ptr)
功能:终止调用线程
Rval_ptr:线程退出返回值的指针
实例分析thrread_exit.c
调用线程打印出东西后,通过return结束线程
5
线程等待:pthread_join
#include<pthread.h>
int pthread_join(pthread_t tid,void**rval_ptr)
功能:阻塞调用线程,直到指定的线程终止
Tid:等待退出的线程id
Rval_ptr:线程退出的返回值的指针。
实例分析pthread_join.c
【1】// pthread_join(pth, NULL);
进程打印后休眠时,线程打印
线程打印后休眠时,进程打印两者互换打印
【2】
// pthread_join(pth, NULL);
// sleep(1);
如果同时注释掉上面两个,则进程执行完,返回后,进程结束同时带着线程结束,线程没打印
6
线程标识
#include<pthread.h>
pthread_t pthread_self(void)
功能:
获取调用线程的thread identifier
【1】
[root@embedclub duoxiancheng]# ./thread_id
Main thread is starting ...
The main process's pid is 15472
New thread ....
This thread's id is 3077995376
The process pid is 15472
获取的线程id和获取的进程id一样
7
清除,释放资源
从pthread_cleanup_push的调用点到pthread_cleanup_pop之间的程序中的终止动作都将执行
void pthread_cleanup_push(void(*rtn)(void*),void*arg)
功能:将清除函数压入清除栈
Rtn;清除函数
Arg:清除函数的参数
8
void pthread_cleanup_pop(int execute)
功能:将清除函数弹出栈
参数:execute执行到pthread_cleanup_pop()时是否在弹出清除函数的同时执行该函
非0:执行
0:不执行
实例分析:
【1】从pthread_cleanup_push的调用点到pthread_cleanup_pop之间的程序中的终止动作都将执行。。不包括return.so当有return,并不执行pthread_cleanup_push所指定的清理函数
【2】栈,先进后出;