linux进程与线程的区别

个人理解,仅供自己参考。

本文参考

http://www.cnblogs.com/blueclue/archive/2010/07/16/1778855.html

http://blog.csdn.net/forrest2009/article/details/6413756

linux内核修炼之道


linux中,进程(process)是具有独立空间,process之间可以互不干扰地运行的基本单位。它们之间通过进程间通讯(IPC)传递数据,除此之外,不会有任何干扰,所以安全性好。而线程(Thread)是进程里面的,用来调度procedures的基本单位,它是:进程里面的一个负责处理某个步骤的基本单位。所以,线程是进程的一部分。

那为啥要区分进程和线程?其实,一开始没有线程这个概念,最早的工程师发现进程间通讯有一定缺陷,需要弥补,所以才改进了进程,把进程这个整体分块了!进程的缺陷是什么呢?

1.进程间通讯复杂,且CPU开销大。如果只是做简单的1+1运算,最好不要劳烦进程间通讯了,最好进程里面可以自己计算。

2.用fork()函数产生一个子进程,内存和CPU开销相当大,因为有大量的数据要copy。(为了有直观的感受,请参照本文结尾的代码,我和我的小伙伴都惊呆了)

这时,会产生疑问,开销大是个什么概念?我们看看进程和线程的数据结构:

 


再来看看线程Thread是怎么藏在进程Process里的

《程序员自我修养》中截图,展示了“进程内”的多线程,“进程空间”是给这个线程用的独立空间,给这个进程用的,不与线程共享。代码/数据/堆和打开的文件是可以共享的。


可见,Thread只需要堆栈指针、程序计数寄存器、一些优先级属性、等待序列和阻塞信号、thread自身的数据。

而Process的组成必须包括以下多出的部分:进程、进程群、用户、群组信息,环境,工作目录,Heap(堆,这个要很大空间),文件描述符,共享库,IPC工具。

 

因此,process内存开销大,通讯复杂的特点,使得工程师们想出了Thread这个东西。Process的开销是Thread的30倍。

Thread可以节省内存空间,创建简单,通讯简单,因此可以快速反应,处理速度可以提升10-100倍。但是因为Thread之间不是独立的,共用堆里面的数据,很可能产生冲突,所以thread要考虑同步的问题,不然数据会不安全。


自己的理解

什么是程序

程序是存储在存储介质上的可执行文件,是代码和数据的集合,程序装载进内存后,可以执行,是程序的动态实体。实体是个什么东西?自己体会吧。

什么是进程?进程对应着程序,程序是静态的代码,而进程就是这个代码实例化,动态化后,转成二进制在内存和CPU里面跑的程序,它有独立的空间,多个进程间需要特殊的IPC工具才能通讯。进程不但是数据和代码的集合,还可以打开文件,挂起信号,管理和保存堆栈信息等,这部分功能就是进程的动态特征。可见,它是系统分配内存资源的最小单位。相对于线程,不会再给它分配内存资源,线程只是在进程这个房间里面跑,利用进程已经获得的资源,所以说,进程才是系统分配资源的最小单位,而线程不是。


那线程是什么?一个进程可以分为两个部分:线程集合和资源集合。线程是进程的动态对象,是一组独立的指令流,多个线程共享进程中的资源。所有进程都拥有至少一个线程。相对于进程是资源管理的最小单位,线程是程序执行的最小单位。这样理解吧,程序有很多函数,我们可以按顺序地执行完,这样相当于单进程单线程。但我们写程序,函数经常是可以并行运作的,所以我们用线程这种技术,独立地运行可以并行操作的函数。就因为这种进程里面的并行操作,我们定义了最小的程序执行单位,那就是线程。

反过来想,如果进程是最小的程序执行单位,那会什么情况?相当于一个进程执行所有函数,就没有了并发处理的概念了嘛,处理速度就上不去。

 

重点:从linux内核来看,并没有线程和进程之分,没有线程的数据结构,linux内核里,线程只是共用数据空间的进程,这样的线程也称为轻量级的进程。参考最下面的进程代码,里面有thread_group数据链表。 同一进程的线程就被存放在这个链表中。线程是用户空间的概念,Thread到轻量级process的转换是通过POSIX库实现的,对应项目为:LinuxThreads.

说到最后,其实process和thread的区别很简单,thread就是为了节省空间,通过thread之间共用数据和堆栈,减少处理数据时候的数据copy,即减少了数据通讯,从而既提高内存使用效率,又减少了CPU的调度任务,从而提升了处理速度。

请想想,其实process和thread在抽象层面是超级简单的东西,只是我们不熟悉它的数据结构,操作流程,所以觉得好难区分。

我把它的抽象过程类比为如下:

 一个人代表一个thread,一个办公室就是一个process,多个人在一个办公室就是多线程,一个人在一个办公室工作就是单线程。

假设一个公司有这样一个部门:他们本来一个人一个办公室,这样就要求他们之间通讯要发邮件,打电话。但是,有一天,他们发现这样效率很低,例如我想给某位大神看一个高清视频,我还得copy到u盘,然后拿到它办公室,它再copy下来看。这时,他们灵机一动,不如把办公室扩大一点,1个组一个办公室吧,反正大家的工作是密切相关的。 这样,有什么邮件、图片、视频、开发工具,大家从座位上移步就可以看了,不需要走出办公室。这样,这个公司就从没有线程的概念,发展到有多线程概念了。

这个例子好像很弱智,但不就是thread产生的原理嘛。


进程的数据结构代码

include/linux/sched.h

 

struct task_struct {
	volatile long state;	/* -1 unrunnable, 0 runnable, >0 stopped */
	void *stack;
	atomic_t usage;
	unsigned int flags;	/* per process flags, defined below */
	unsigned int ptrace;

	int lock_depth;		/* BKL lock depth */

#ifdef CONFIG_SMP
#ifdef __ARCH_WANT_UNLOCKED_CTXSW
	int oncpu;
#endif
#endif

	int prio, static_prio, normal_prio;
	unsigned int rt_priority;
	const struct sched_class *sched_class;
	struct sched_entity se;
	struct sched_rt_entity rt;

#ifdef CONFIG_PREEMPT_NOTIFIERS
	/* list of struct preempt_notifier: */
	struct hlist_head preempt_notifiers;
#endif

	/*
	 * fpu_counter contains the number of consecutive context switches
	 * that the FPU is used. If this is over a threshold, the lazy fpu
	 * saving becomes unlazy to save the trap. This is an unsigned char
	 * so that after 256 times the counter wraps and the behavior turns
	 * lazy again; this to deal with bursty apps that only use FPU for
	 * a short time
	 */
	unsigned char fpu_counter;
#ifdef CONFIG_BLK_DEV_IO_TRACE
	unsigned int btrace_seq;
#endif

	unsigned int policy;
	cpumask_t cpus_allowed;

#ifdef CONFIG_TREE_PREEMPT_RCU
	int rcu_read_lock_nesting;
	char rcu_read_unlock_special;
	struct rcu_node *rcu_blocked_node;
	struct list_head rcu_node_entry;
#endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */

#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
	struct sched_info sched_info;
#endif

	struct list_head tasks;
	struct plist_node pushable_tasks;

	struct mm_struct *mm, *active_mm;
#if defined(SPLIT_RSS_COUNTING)
	struct task_rss_stat	rss_stat;
#endif
/* task state */
	int exit_state;
	int exit_code, exit_signal;
	int pdeath_signal;  /*  The signal sent when the parent dies  */
	/* ??? */
	unsigned int personality;
	unsigned did_exec:1;
	unsigned in_execve:1;	/* Tell the LSMs that the process is doing an
				 * execve */
	unsigned in_iowait:1;


	/* Revert to default priority/policy when forking */
	unsigned sched_reset_on_fork:1;

	pid_t pid;
	pid_t tgid;

#ifdef CONFIG_CC_STACKPROTECTOR
	/* Canary value for the -fstack-protector gcc feature */
	unsigned long stack_canary;
#endif

	/* 
	 * pointers to (original) parent process, youngest child, younger sibling,
	 * older sibling, respectively.  (p->father can be replaced with 
	 * p->real_parent->pid)
	 */
	struct task_struct *real_parent; /* real parent process */
	struct task_struct *parent; /* recipient of SIGCHLD, wait4() reports */
	/*
	 * children/sibling forms the list of my natural children
	 */
	struct list_head children;	/* list of my children */
	struct list_head sibling;	/* linkage in my parent's children list */
	struct task_struct *group_leader;	/* threadgroup leader */

	/*
	 * ptraced is the list of tasks this task is using ptrace on.
	 * This includes both natural children and PTRACE_ATTACH targets.
	 * p->ptrace_entry is p's link on the p->parent->ptraced list.
	 */
	struct list_head ptraced;
	struct list_head ptrace_entry;

	/*
	 * This is the tracer handle for the ptrace BTS extension.
	 * This field actually belongs to the ptracer task.
	 */
	struct bts_context *bts;

	/* PID/PID hash table linkage. */
	struct pid_link pids[PIDTYPE_MAX];
	struct list_head thread_group;

	struct completion *vfork_done;		/* for vfork() */
	int __user *set_child_tid;		/* CLONE_CHILD_SETTID */
	int __user *clear_child_tid;		/* CLONE_CHILD_CLEARTID */

	cputime_t utime, stime, utimescaled, stimescaled;
	cputime_t gtime;
#ifndef CONFIG_VIRT_CPU_ACCOUNTING
	cputime_t prev_utime, prev_stime;
#endif
	unsigned long nvcsw, nivcsw; /* context switch counts */
	struct timespec start_time; 		/* monotonic time */
	struct timespec real_start_time;	/* boot based time */
/* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */
	unsigned long min_flt, maj_flt;

	struct task_cputime cputime_expires;
	struct list_head cpu_timers[3];

/* process credentials */
	const struct cred *real_cred;	/* objective and real subjective task
					 * credentials (COW) */
	const struct cred *cred;	/* effective (overridable) subjective task
					 * credentials (COW) */
	struct mutex cred_guard_mutex;	/* guard against foreign influences on
					 * credential calculations
					 * (notably. ptrace) */
	struct cred *replacement_session_keyring; /* for KEYCTL_SESSION_TO_PARENT */

	char comm[TASK_COMM_LEN]; /* executable name excluding path
				     - access with [gs]et_task_comm (which lock
				       it with task_lock())
				     - initialized normally by setup_new_exec */
/* file system info */
	int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc stuff */
	struct sysv_sem sysvsem;
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
/* hung task detection */
	unsigned long last_switch_count;
#endif
/* CPU-specific state of this task */
	struct thread_struct thread;
/* filesystem information */
	struct fs_struct *fs;
/* open file information */
	struct files_struct *files;
/* namespaces */
	struct nsproxy *nsproxy;
/* signal handlers */
	struct signal_struct *signal;
	struct sighand_struct *sighand;

	sigset_t blocked, real_blocked;
	sigset_t saved_sigmask;	/* restored if set_restore_sigmask() was used */
	struct sigpending pending;

	unsigned long sas_ss_sp;
	size_t sas_ss_size;
	int (*notifier)(void *priv);
	void *notifier_data;
	sigset_t *notifier_mask;
	struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
	uid_t loginuid;
	unsigned int sessionid;
#endif
	seccomp_t seccomp;

/* Thread group tracking */
   	u32 parent_exec_id;
   	u32 self_exec_id;
/* Protection of (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed,
 * mempolicy */
	spinlock_t alloc_lock;

#ifdef CONFIG_GENERIC_HARDIRQS
	/* IRQ handler threads */
	struct irqaction *irqaction;
#endif

	/* Protection of the PI data structures: */
	raw_spinlock_t pi_lock;

#ifdef CONFIG_RT_MUTEXES
	/* PI waiters blocked on a rt_mutex held by this task */
	struct plist_head pi_waiters;
	/* Deadlock detection and priority inheritance handling */
	struct rt_mutex_waiter *pi_blocked_on;
#endif

#ifdef CONFIG_DEBUG_MUTEXES
	/* mutex deadlock detection */
	struct mutex_waiter *blocked_on;
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
	unsigned int irq_events;
	unsigned long hardirq_enable_ip;
	unsigned long hardirq_disable_ip;
	unsigned int hardirq_enable_event;
	unsigned int hardirq_disable_event;
	int hardirqs_enabled;
	int hardirq_context;
	unsigned long softirq_disable_ip;
	unsigned long softirq_enable_ip;
	unsigned int softirq_disable_event;
	unsigned int softirq_enable_event;
	int softirqs_enabled;
	int softirq_context;
#endif
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
	u64 curr_chain_key;
	int lockdep_depth;
	unsigned int lockdep_recursion;
	struct held_lock held_locks[MAX_LOCK_DEPTH];
	gfp_t lockdep_reclaim_gfp;
#endif

/* journalling filesystem info */
	void *journal_info;

/* stacked block device info */
	struct bio_list *bio_list;

/* VM state */
	struct reclaim_state *reclaim_state;

	struct backing_dev_info *backing_dev_info;

	struct io_context *io_context;

	unsigned long ptrace_message;
	siginfo_t *last_siginfo; /* For ptrace use.  */
	struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
	u64 acct_rss_mem1;	/* accumulated rss usage */
	u64 acct_vm_mem1;	/* accumulated virtual memory usage */
	cputime_t acct_timexpd;	/* stime + utime since last update */
#endif
#ifdef CONFIG_CPUSETS
	nodemask_t mems_allowed;	/* Protected by alloc_lock */
	int cpuset_mem_spread_rotor;
#endif
#ifdef CONFIG_CGROUPS
	/* Control Group info protected by css_set_lock */
	struct css_set *cgroups;
	/* cg_list protected by css_set_lock and tsk->alloc_lock */
	struct list_head cg_list;
#endif
#ifdef CONFIG_FUTEX
	struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
	struct compat_robust_list_head __user *compat_robust_list;
#endif
	struct list_head pi_state_list;
	struct futex_pi_state *pi_state_cache;
#endif
#ifdef CONFIG_PERF_EVENTS
	struct perf_event_context *perf_event_ctxp;
	struct mutex perf_event_mutex;
	struct list_head perf_event_list;
#endif
#ifdef CONFIG_NUMA
	struct mempolicy *mempolicy;	/* Protected by alloc_lock */
	short il_next;
#endif
	atomic_t fs_excl;	/* holding fs exclusive resources */
	struct rcu_head rcu;

	/*
	 * cache last used pipe for splice
	 */
	struct pipe_inode_info *splice_pipe;
#ifdef	CONFIG_TASK_DELAY_ACCT
	struct task_delay_info *delays;
#endif
#ifdef CONFIG_FAULT_INJECTION
	int make_it_fail;
#endif
	struct prop_local_single dirties;
#ifdef CONFIG_LATENCYTOP
	int latency_record_count;
	struct latency_record latency_record[LT_SAVECOUNT];
#endif
	/*
	 * time slack values; these are used to round up poll() and
	 * select() etc timeout values. These are in nanoseconds.
	 */
	unsigned long timer_slack_ns;
	unsigned long default_timer_slack_ns;

	struct list_head	*scm_work_list;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
	/* Index of current stored address in ret_stack */
	int curr_ret_stack;
	/* Stack of return addresses for return function tracing */
	struct ftrace_ret_stack	*ret_stack;
	/* time stamp for last schedule */
	unsigned long long ftrace_timestamp;
	/*
	 * Number of functions that haven't been traced
	 * because of depth overrun.
	 */
	atomic_t trace_overrun;
	/* Pause for the tracing */
	atomic_t tracing_graph_pause;
#endif
#ifdef CONFIG_TRACING
	/* state flags for use by tracers */
	unsigned long trace;
	/* bitmask of trace recursion */
	unsigned long trace_recursion;
#endif /* CONFIG_TRACING */
#ifdef CONFIG_CGROUP_MEM_RES_CTLR /* memcg uses this to do batch job */
	struct memcg_batch_info {
		int do_batch;	/* incremented when batch uncharge started */
		struct mem_cgroup *memcg; /* target memcg of uncharge */
		unsigned long bytes; 		/* uncharged usage */
		unsigned long memsw_bytes; /* uncharged mem+swap usage */
	} memcg_batch;
#endif
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值