线程的概念:线程是操作系统调度的最小单元,在Linux平台下线程是进程的基本单位。
线程间的很多资源都是共享的,例如 文件描述符,每种信号的处理方式,当前工作目录,用户id和组id,但线程有的资源是各有一份的,比如线程id,上下文,栈空间等等。。。
线程和进程类似,有创建和终止以及等待。
线程里左右函数的头文件均为#include
1 #include<stdio.h>
2 #include<pthread.h>
3 #include<stdlib.h>
4 int count=0;
5 void * fun(void * arg)
6 {
7
8 }
9
10 void * thread_run(void* arg)
11 {
12 int i=(int)arg;
13 while(1)
14 {
15 count++;
16 printf("this is thead,%d,thread:%d\n",i,pthread_self());
17 sleep(1);
18 if(count==10)
19 {
20 // exit(1);
21 // return (void*)20;
22 pthread_exit((void*)1);
23 }
24 }
25 }
26
27 int main()
28 {
29 pthread_t id;
30 pthread_create(&id,NULL,thread_run,(void*)1);
31 /* while(1)
32 {
33 sleep(1);
34 printf("this is main thread:pid count: %d\n",count);
35 if(count==5)
36 {
37 pthread_cancel(id);
38 }
39 printf("ret: %d\n",(int)ret);
40 } */
41 void* ret=NULL;
42 while(1)
43 {
44 pthread_join(id,&ret);
45 pthread_cancel(id);
46 }
47 printf("ret: %d\n",(int)ret);
48 sleep(1);
49 return 0;
50 }
终止线程
pthread_exit(void* retval);
pthread_cancel(pthread_t thread);
终止线程有三种方法:
1、从线程函数return
2、一个线程可以自己调用pthread_exit终止自己
3、线程可以调用pthread_cancel来终止同一进程中的其他线程
注意:pthread_exit和return 返回的指针所指向的内存单元必须是全局变量或者是malloc分配的。
线程等待
pthread_join(pthread_t thread,void** retval);
调用该函数的线程将挂起等待,知道id为thread的线程终止。thread线程以不同的方法终止,通过pthread_join得到的终止状态是不同的,总结如下:
1、如果thread线程通过return 返回,value_ptr所指向的单元存放的就是thread线程的返回值
2、如果thread线程被别的进程调用Pthread_cancel异常终止,value_ptr所指向的单元存放的是常数PTHREAD_CANCELED
3、如果线程是自己调用pthread_exit函数终止,value_ptr所指向的单元存放的是pthread_exit的参数。
总结:通过pthread_self()打印自己的线程id,如果在任一进程内调用exit或_exit,则整个进程的所有线程都将终止,由于从main中调用return也相当于调用exit,为了防止线程没有得到执行就被终止,所以一般我们会加上sleep或者加上Pthread_join。
随后再更……..