多线程的那点儿事(基础篇)

多线程编程是现代软件技术中很重要的一个环节。要弄懂多线程,这就要牵涉到多进程?当然,要了解到多进程,就要涉及到操作系统。不过大家也不要紧张,听我慢慢道来。这其中的环节其实并不复杂。

    (1)单CPU下的多线程

     在没有出现多核CPU之前,我们的计算资源是唯一的。如果系统中有多个任务要处理的话,那么就需要按照某种规则依次调度这些任务进行处理。什么规则呢?可以是一些简单的调度方法,比如说

    1)按照优先级调度

    2)按照FIFO调度

    3)按照时间片调度等等

    当然,除了CPU资源之外,系统中还有一些其他的资源需要共享,比如说内存、文件、端口、socket等。既然前面说到系统中的资源是有限的,那么获取这些资源的最小单元体是什么呢,其实就是进程。

    举个例子来说,在linux上面每一个享有资源的个体称为task_struct,实际上和我们说的进程是一样的。我们可以看看task_structlinux 0.11代码)都包括哪些内容,

  1. struct task_struct {  
  2. /* these are hardcoded - don't touch */  
  3.     long state; /* -1 unrunnable, 0 runnable, >0 stopped */  
  4.     long counter;  
  5.     long priority;  
  6.     long signal;  
  7.     struct sigaction sigaction[32];  
  8.     long blocked;   /* bitmap of masked signals */  
  9. /* various fields */  
  10.     int exit_code;  
  11.     unsigned long start_code,end_code,end_data,brk,start_stack;  
  12.     long pid,father,pgrp,session,leader;  
  13.     unsigned short uid,euid,suid;  
  14.     unsigned short gid,egid,sgid;  
  15.     long alarm;  
  16.     long utime,stime,cutime,cstime,start_time;  
  17.     unsigned short used_math;  
  18. /* file system info */  
  19.     int tty;        /* -1 if no tty, so it must be signed */  
  20.     unsigned short umask;  
  21.     struct m_inode * pwd;  
  22.     struct m_inode * root;  
  23.     struct m_inode * executable;  
  24.     unsigned long close_on_exec;  
  25.     struct file * filp[NR_OPEN];  
  26. /* ldt for this task 0 - zero 1 - cs 2 - ds&ss */  
  27.     struct desc_struct ldt[3];  
  28. /* tss for this task */  
  29.     struct tss_struct tss;  
  30. };  
	struct task_struct {
	/* these are hardcoded - don't touch */
		long state;	/* -1 unrunnable, 0 runnable, >0 stopped */
		long counter;
		long priority;
		long signal;
		struct sigaction sigaction[32];
		long blocked;	/* bitmap of masked signals */
	/* various fields */
		int exit_code;
		unsigned long start_code,end_code,end_data,brk,start_stack;
		long pid,father,pgrp,session,leader;
		unsigned short uid,euid,suid;
		unsigned short gid,egid,sgid;
		long alarm;
		long utime,stime,cutime,cstime,start_time;
		unsigned short used_math;
	/* file system info */
		int tty;		/* -1 if no tty, so it must be signed */
		unsigned short umask;
		struct m_inode * pwd;
		struct m_inode * root;
		struct m_inode * executable;
		unsigned long close_on_exec;
		struct file * filp[NR_OPEN];
	/* ldt for this task 0 - zero 1 - cs 2 - ds&ss */
		struct desc_struct ldt[3];
	/* tss for this task */
		struct tss_struct tss;
	};

    每一个task都有自己的pid,在系统中资源的分配都是按照pid进行处理的。这也就说明,进程确实是资源分配的主体。

    这时候,可能有朋友会问了,既然task_struct是资源分配的主体,那为什么又出来thread?为什么系统调度的时候是按照thread调度,而不是按照进程调度呢?原因其实很简单,进程之间的数据沟通非常麻烦,因为我们之所以把这些进程分开,不正是希望它们之间不要相互影响嘛。

    假设是两个进程之间数据传输,那么需要如果需要对共享数据进行访问需要哪些步骤呢,

    1)创建共享内存

    2)访问共享内存->系统调用->读取数据

    3)写入共享内存->系统调用->写入数据

    要是写个代码,大家可能就更明白了,

  1. #include <unistd.h>   
  2. #include <stdio.h>   
  3.   
  4. int value = 10;  
  5.   
  6. int main(int argc, char* argv[])  
  7. {  
  8.     int pid = fork();  
  9.     if(!pid){  
  10.         Value = 12;  
  11.         return 0;  
  12.     }  
  13.     printf("value = %d\n", value);  
  14.     return 1;  
  15. }  
	#include <unistd.h>
	#include <stdio.h>
	
	int value = 10;
	
	int main(int argc, char* argv[])
	{
	    int pid = fork();
	    if(!pid){
	        Value = 12;
	        return 0;
	    }
	    printf("value = %d\n", value);
	    return 1;
	}

    上面的代码是一个创建子进程的代码,我们发现打印的value数值还是10。尽管中间创建了子进程,修改了value的数值,但是我们发现打印下来的数值并没有发生改变,这就说明了不同的进程之间内存上是不共享的。

    那么,如果修改成thread有什么好处呢?其实最大的好处就是每个thread除了享受单独cpu调度的机会,还能共享每个进程下的所有资源。要是调度的单位是进程,那么每个进程只能干一件事情,但是进程之间是需要相互交互数据的,而进程之间的数据都需要系统调用才能应用,这在无形之中就降低了数据的处理效率。


    (2)多核CPU下的多线程

    没有出现多核之前,我们的CPU实际上是按照某种规则对线程依次进行调度的。在某一个特定的时刻,CPU执行的还是某一个特定的线程。然而,现在有了多核CPU,一切变得不一样了,因为在某一时刻很有可能确实是n个任务在n个核上运行。我们可以编写一个简单的open mp测试一下,如果还是一个核,运行的时间就应该是一样的。

  1. #include <omp.h>   
  2. #define MAX_VALUE 10000000   
  3.   
  4. double _test(int value)  
  5. {  
  6.     int index;  
  7.     double result;  
  8.   
  9.     result = 0.0;  
  10.     for(index = value + 1; index < MAX_VALUE; index +=2 )  
  11.         result += 1.0 / index;  
  12.   
  13.     return result;  
  14. }  
  15.   
  16. void test()  
  17. {  
  18.     int index;  
  19.     int time1;  
  20.     int time2;  
  21.     double value1,value2;  
  22.     double result[2];  
  23.   
  24.     time1 = 0;  
  25.     time2 = 0;  
  26.   
  27.     value1 = 0.0;  
  28.     time1 = GetTickCount();  
  29.     for(index = 1; index < MAX_VALUE; index ++)  
  30.         value1 += 1.0 / index;  
  31.   
  32.     time1 = GetTickCount() - time1;  
  33.   
  34.     value2 = 0.0;  
  35.     memset(result , 0, sizeof(double) * 2);  
  36.     time2 = GetTickCount();  
  37.   
  38. #pragma omp parallel for   
  39.     for(index = 0; index < 2; index++)  
  40.         result[index] = _test(index);  
  41.   
  42.     value2 = result[0] + result[1];  
  43.     time2 = GetTickCount() - time2;  
  44.   
  45.     printf("time1 = %d,time2 = %d\n",time1,time2);  
  46.     return;  
  47. }  
#include <omp.h>
#define MAX_VALUE 10000000

double _test(int value)
{
	int index;
	double result;

	result = 0.0;
	for(index = value + 1; index < MAX_VALUE; index +=2 )
		result += 1.0 / index;

	return result;
}

void test()
{
	int index;
	int time1;
	int time2;
	double value1,value2;
	double result[2];

    time1 = 0;
	time2 = 0;

	value1 = 0.0;
	time1 = GetTickCount();
	for(index = 1; index < MAX_VALUE; index ++)
		value1 += 1.0 / index;

	time1 = GetTickCount() - time1;

	value2 = 0.0;
	memset(result , 0, sizeof(double) * 2);
	time2 = GetTickCount();

#pragma omp parallel for
	for(index = 0; index < 2; index++)
		result[index] = _test(index);

	value2 = result[0] + result[1];
	time2 = GetTickCount() - time2;

	printf("time1 = %d,time2 = %d\n",time1,time2);
	return;
}

    (3)多线程编程

为什么要多线程编程呢?这其中的原因很多,我们可以举例解决

    1)有的是为了提高运行的速度,比如多核cpu下的多线程

    2)有的是为了提高资源的利用率,比如在网络环境下下载资源时,时延常常很高,我们可以通过不同的thread从不同的地方获取资源,这样可以提高效率

    3)有的为了提供更好的服务,比如说是服务器

    4)其他需要多线程编程的地方等等


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值