进程和线程的主要差别在于它们是不同的操作系统资源管理方式。进程有独立的地址空间,一个进程崩溃后,在保护模式下不会对其它进程产生影响,而线程只是一个进程中的不同执行路径。线程有自己的堆栈和局部变量,但线程之间没有单独的地址空间,一个线程死掉就等于整个进程死掉,所以多进程的程序要比多线程的程序健壮,但在进程切换时,耗费资源较大,效率要差一些。但对于一些要求同时进行并且又要共享某些变量的并发操作,只能用线程,不能用进程。
1) 简而言之,一个程序至少有一个进程,一个进程至少有一个线程.
2) 线程的划分尺度小于进程,使得多线程程序的并发性高。
3) 另外,进程在执行过程中拥有独立的内存单元,而多个线程共享内存,从而极大地提高了程序的运行效率。
4) 线程在执行过程中与进程还是有区别的。每个独立的线程有一个程序运行的入口、顺序执行序列和程序的出口。但是线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制。
5) 从逻辑角度来看,多线程的意义在于一个应用程序中,有多个执行部分可以同时执行。但操作系统并没有将多个线程看做多个独立的应用,来实现进程的调度和管理以及资源分配。这就是进程和线程的重要区别
同一进程的多个线程之间共享以下进程资源和环境:
1. 文件描述符表
2. 每种信号的处理方式(SIG_IGN、SIG_DFL或者自定义的信号处理函数)
3. 当前工作目录
4. 用户id和组id
同一进程的多个线程之间的私有资源:
1. 线程id(是一个正整数,仅在当前进程内有效,用来标识线程)
2. 上下文,包括各种寄存器的值、程序计数器和栈指针
3. 栈空间
4. errno变量
5. 信号屏蔽字
线程的创建
6. 调度优先级
#include<stdio.h>
2 #include<pthread.h>
3 #include<unistd.h>
4
5
6 void* thread1(void* vall)
7 {
8 printf("thread1 is returning\n");
9 printf("%s:pid is %d,tid is %u\n",(char*)vall,getpid(),pthread_self());
10 pthread_exit((void*)0);//shutdown thread1,and return
11 }
12
13 void* thread2(void* val2)
14 {
15 printf("thread2 exiting\n");
16 printf("%s:pid is %d,tid is %u\n",(char*)val2,getpid(),pthread_self());
17 pthread_exit((void*)2);//shutdown thread2,pthread_exit
18 }
19 void* thread3(void* val3)
20 {
21 printf("%s:pid is %d,tid is %u\n",(char*)val3,getpid(),pthread_self());
22 while(1)
23 {
24
25 printf("thread3 is running ,waiting for e canceled\n");//shutdown thread3,cancel byh other thread
26
27 sleep(1);
28 }
29 }
30
31
32 int main()
33 {
34 pthread_t tid1;
35 pthread_t tid2;
36 pthread_t tid3;
37 void* ret;
38
39 pthread_create(&tid1,NULL,thread1,"thread1");//new pthread1
40 pthread_join(tid1,&ret);//wait thread2
41 printf("thread1 return ,return code is%d\n",(int)ret);
42
43 pthread_create (&tid2,NULL,thread2,"thread2");//new thread2
44 pthread_join(tid2,&ret);//wait thread2
45 printf("thread2 exit,exit code is%d\n",(int)ret);
46
47 pthread_create(&tid3,NULL,thread3,"thread3");
48 sleep(3);
49 pthread_cancel(tid3);
50 pthread_join(tid3,&ret);
51 printf("thread3 cancel,cancel code is%d\n",(int)ret);
52
53 printf("main thread run:pid is%d,tid is%u\n",getpid(),pthread_self());
54
55 return 0;
56 }
执行结果如下:
在编译时由于pthread不是linux下默认的库,所以需要-lpthread