日期:2014-05-16  浏览次数:20629 次

linux线程应用

一、线程(pthread)的概念

产生60年代,遵循POSIX线程接口

二、线程与进程的区别

1、进程:在子进程中需要分配新的地址空间,  拷贝代码段、数据段、堆栈段,进程间通过IPC通信。线程:实现全部共享。总之,线程节约资源

2、一个进程包括多个线程,线程之间地址相同,线程开销小

3、独立的数据只能通进程,而同一线程则共享数据。

4、进程:资源分配的基本单位。线程:调度的基本单位

三、线程创建

1、头文件:#include<thread.h>  链接库  -lpthread (gcc -o des src -lpthread)

2、int pthread_create(pthread_t * tidp,const pthread_attr_t *attr,void *(*start_rtn)(void),void *arg)(ID号,属性NULL,线程执行的指针函数,参数指针)

四、线程终止

1、线程使用exit()和_exit()终止,正常终止的三种方式:(1)、例程中终止 (2)、线程被另一个进程终止(3)、线程调用pthread_exit()函数

2、线程退出

void pthread_exit(void * rval_ptr)  其中:rval_ptr为退出时返回值的指针

五、线程等待

int pthread_join(pthread_t tid,void **rval_ptr)

功能:当阻塞时,调用线程,直到指定的线程终止

六、线程标识

pthread_t pthread_self(void)  返回ID

七、线程清除

1、正常终止(pthread_exit、return )

    注意:return  时,不执行清理函数pthread_cleanup_XXX。其他,则执行清理函数(前提:pop(0)为0)

  异常终止  :自身运行出错,返回空指针等,执行清理函数。

2、void pthread_cleanup_push(void (*rtn)(void *),void *arg)

   void pthread_cleanup_pop(int execute)

    (execute 为0表示执行,为1表示不执行)

实例代码

#include<stdio.h>
#include<unistd.h>
#include<pthread.h>

void *fun(void *p)
{
int i;
int j=*((int*)p); //把P强制转换成void*类型,并且返回其所指的对象,赋值给j;
//int *num;
//num=(int *)p;
//int j=*num;
for(i=0;i<10;i++)
 {
    printf("%d\n",j++);
 }
pthread_exit(NULL);  //结束当前线程
}
int main()
{
int m;
int a=1;
int b=101;
int *attr=&a;
pthread_t p_thread; 
m=pthread_create(&p_thread,NULL,(void *)fun,(void*)attr);  //创建新线程 (pthread用来保存新线程的ID,NULL为新线程的属性为默认,fun是新线程执行的函数必须是void*(void  ))类型,(void*)&a是前面函数的实参)    m为创建成功与否的返回值
sleep(1);
pthread_cancel(p_thread); //强制结束p_thread这个线程
fun((void*)&b);//主线程调用fun()函数
}

/**********************
  test thread's ID
  thread_ID.c
  by zhaochuang 2013.4.3
  ********************/
 #include <stdio.h>
 #include <pthread.h>

 void *thread()
 {
 int i;
 //sleep(1);
 for(i=0;i<3;i++)
 printf("This is a pthread %d\n",i);
 printf("the slave process ID is %d\n",getpid());
 printf("the slave thread ID is %d\n",pthread_self());
 }
 
int main(void)
 {
 pthread_t id=100;
 int i=100;
 int ret=100;
 int ptr=100;
// int result=100;
 printf("id=%d;i=%d;ret=%d;ptr=%d\n",id,i,ret,ptr);
 //查看线程返回值一般为0
 ret=pthread_create(&id,NULL,(void *) thread,NULL);
 printf("id=%d;i=%d;ret=%d;ptr=%d\n",id,i,ret,ptr);
 if(ret!=0){
 printf ("Create pthread error!\n");
 exit (1);
 }
 for(i=0;i<3;i++)
 printf("This is the main process %d\n",i);
//获取主进程ID
 printf("the master process PID is %d\n",getpid());
//获取主线程ID
 printf("the thread ID is %d\n",pthread_self());
//主线程等待新创建的线程的结束才结束,其中ID为主线程(等待线程)的id
 pthread_join(id,NULL);
//printf("id=%d;ptr=%d;result=%d\n",id,ptr,result);
 return (0);
 }