最常见的程序员面试题(5)Java/C++线程同步

Java线程同步是服务器技术的基础问题。大型网络服务器/应用服务器/数据库等均包含复杂的多线程实现。

(1) 最常见的多线程同步的问题是和Singleton设计模式相关的。为了保证多线程在访问Singleton实例的时候没有多线程冲突,需要对代码进行保护。

  1. public class my {  
  2.     public static void main(String[] args) {  
  3.         my.Singleton.GetInstance();  
  4.     }  
  5.     static class Singleton{  
  6.         private static volatile Singleton inst=null;  
  7.         public static Singleton GetInstance(){  
  8.             if(inst==null){  
  9.                 synchronized(Singleton.class){//JVM memory barrier   
  10.                     inst=new Singleton();  
  11.                 }  
  12.             }  
  13.             return inst;  
  14.         }  
  15.         Singleton(){System.out.println("ctor");}  
  16.     }  
  17. }  
public class my {
	public static void main(String[] args) {
		my.Singleton.GetInstance();
	}
	static class Singleton{
		private static volatile Singleton inst=null;
		public static Singleton GetInstance(){
			if(inst==null){
				synchronized(Singleton.class){//JVM memory barrier
					inst=new Singleton();
				}
			}
			return inst;
		}
		Singleton(){System.out.println("ctor");}
	}
}
(2) Singleton的例子很简单,因为多线程保护集中在同一个函数当中。如果这种保护要跨越多个函数调用,那么"关键段"或者"synchronized"代码就失效了,如下所示。例如,对于银行ATM而言,"存款"和"取款"者两个函数调用是不能同时进行的,必须存在一个能管理全局的资源锁。
  1. public class ATM{  
  2.     int m_nAmount;  
  3.     ATM(int m){  
  4.         m_nAmount=m;  
  5.     }  
  6.     class ClientThread1 extends Thread{  
  7.         public void run(){  
  8.             try{  
  9.                 while(true){  
  10.                     Deposit(10);  
  11.                     Thread.sleep(1000);  
  12.                     System.out.println(",thread1:"+m_nAmount);  
  13.                 }  
  14.             }catch(InterruptedException e){  
  15.                   
  16.             }  
  17.         }  
  18.         synchronized void Deposit(int amount){  
  19.             m_nAmount+=amount;  
  20.         }  
  21.     }  
  22.     class ClientThread2 extends Thread{  
  23.         public void run(){  
  24.             try{  
  25.                 while(true){  
  26.                     WithDraw(10);  
  27.                     Thread.sleep(1000);  
  28.                     System.out.println(",thread2:"+m_nAmount);  
  29.                 }  
  30.             }catch(InterruptedException e){  
  31.                   
  32.             }  
  33.         }  
  34.         synchronized void WithDraw(int amount){  
  35.             m_nAmount-=amount;  
  36.         }  
  37.     }  
  38.     public static void main(String[] args) {  
  39.         ATM re=new ATM(100);  
  40.         ATM.ClientThread1 th1= re.new ClientThread1();  
  41.         ATM.ClientThread2 th2= re.new ClientThread2();  
  42.         ATM.ClientThread1 th3= re.new ClientThread1();  
  43.         ATM.ClientThread2 th4= re.new ClientThread2();  
  44.         th1.start();  
  45.         th2.start();  
  46.         th3.start();  
  47.         th4.start();  
  48.     }  
  49. }  
public class ATM{
	int m_nAmount;
	ATM(int m){
		m_nAmount=m;
	}
	class ClientThread1 extends Thread{
		public void run(){
			try{
				while(true){
					Deposit(10);
					Thread.sleep(1000);
					System.out.println(",thread1:"+m_nAmount);
				}
			}catch(InterruptedException e){
				
			}
		}
		synchronized void Deposit(int amount){
			m_nAmount+=amount;
		}
	}
	class ClientThread2 extends Thread{
		public void run(){
			try{
				while(true){
					WithDraw(10);
					Thread.sleep(1000);
					System.out.println(",thread2:"+m_nAmount);
				}
			}catch(InterruptedException e){
				
			}
		}
		synchronized void WithDraw(int amount){
			m_nAmount-=amount;
		}
	}
	public static void main(String[] args) {
		ATM re=new ATM(100);
		ATM.ClientThread1 th1= re.new ClientThread1();
		ATM.ClientThread2 th2= re.new ClientThread2();
		ATM.ClientThread1 th3= re.new ClientThread1();
		ATM.ClientThread2 th4= re.new ClientThread2();
		th1.start();
		th2.start();
		th3.start();
		th4.start();
	}
}

    这段代码的执行结果会像是下面这样:
,thread2:100
,thread2:100
,thread1:90
,thread1:100
,thread2:100
,thread2:90
,thread1:80
,thread1:90
,thread2:100
,thread2:90
,thread1:80
,thread1:90
    原因前面已经说过了,因为无法保证两个函数能被互斥的访问。有一句名言,计算机领域的问题都可以通过引入一个中间层次得以解决,也就是说,为了解决这个问题,java1.5以后引入了新的包concurrent,这个包的内部去声明synchronized就行了。因此上面的代码会变成这样。这保证了没有Deposite或者WithDraw被同时执行造成潜在的数据冲突。多个线程每次只能执行一个Deposite或者WithDraw操作。
  1. import java.util.concurrent.locks.*;  
  2. public class ATM {  
  3.     int m_nAmount=0;  
  4.     Lock m_lock=new ReentrantLock();  
  5.     ATM(int m){  
  6.         m_nAmount=m;  
  7.     }  
  8.     class ClientThread1 extends Thread{  
  9.         public void run(){  
  10.             try{  
  11.                 while(true){  
  12.                     m_lock.lock();  
  13.                     Save(10);  
  14.                     System.out.println(",thread1:"+m_nAmount);  
  15.                     m_lock.unlock();  
  16.                     Thread.sleep(1000);  
  17.                 }  
  18.             }catch(InterruptedException e){}  
  19.         }  
  20.         synchronized void Save(int amount){  
  21.             m_nAmount+=amount;  
  22.         }  
  23.     }  
  24.     class ClientThread2 extends Thread{  
  25.         public void run(){  
  26.             try{  
  27.                 while(true){  
  28.                     m_lock.lock();  
  29.                     WithDraw(10);  
  30.                     System.out.println(",thread2:"+m_nAmount);  
  31.                     m_lock.unlock();  
  32.                     Thread.sleep(1000);  
  33.                 }  
  34.             }catch(InterruptedException e){}  
  35.         }  
  36.         synchronized void WithDraw(int amount){  
  37.             m_nAmount-=amount;  
  38.             if(m_nAmount<0){  
  39.                 System.out.println("failed withdraw");  
  40.             }  
  41.         }  
  42.     }  
  43.     public static void main(String[] args) {  
  44.         ATM re=new ATM(15);  
  45.         ATM.ClientThread1 th1= re.new ClientThread1();  
  46.         ATM.ClientThread2 th2= re.new ClientThread2();  
  47.         ATM.ClientThread1 th3= re.new ClientThread1();  
  48.         ATM.ClientThread2 th4= re.new ClientThread2();  
  49.         th1.start();  
  50.         th2.start();  
  51.         th3.start();  
  52.         th4.start();  
  53.     }  
  54. }  
import java.util.concurrent.locks.*;
public class ATM {
	int m_nAmount=0;
	Lock m_lock=new ReentrantLock();
	ATM(int m){
		m_nAmount=m;
	}
	class ClientThread1 extends Thread{
		public void run(){
			try{
				while(true){
					m_lock.lock();
					Save(10);
					System.out.println(",thread1:"+m_nAmount);
					m_lock.unlock();
					Thread.sleep(1000);
				}
			}catch(InterruptedException e){}
		}
		synchronized void Save(int amount){
			m_nAmount+=amount;
		}
	}
	class ClientThread2 extends Thread{
		public void run(){
			try{
				while(true){
					m_lock.lock();
					WithDraw(10);
					System.out.println(",thread2:"+m_nAmount);
					m_lock.unlock();
					Thread.sleep(1000);
				}
			}catch(InterruptedException e){}
		}
		synchronized void WithDraw(int amount){
			m_nAmount-=amount;
			if(m_nAmount<0){
				System.out.println("failed withdraw");
			}
		}
	}
	public static void main(String[] args) {
		ATM re=new ATM(15);
		ATM.ClientThread1 th1= re.new ClientThread1();
		ATM.ClientThread2 th2= re.new ClientThread2();
		ATM.ClientThread1 th3= re.new ClientThread1();
		ATM.ClientThread2 th4= re.new ClientThread2();
		th1.start();
		th2.start();
		th3.start();
		th4.start();
	}
}


(3) 线程同步的问题,常见的是和synchronized关键字有关的。经典的问题之一是ATM取款机问题。因为windows的线程切换时间在10ms左右,因此下面这个程序就演示了100个线程同时存钱/取钱,最终的结果是不确定的。

  1. public class my{   
  2.      public static void main(String[] args){   
  3.          ATM[] pArr=new ATM[100];   
  4.          for(int i=0;i<pArr.length;++i){   
  5.              pArr[i]=new ATM();   
  6.              pArr[i].start();   
  7.          }  
  8.          try{  
  9.              Thread.sleep(300);  
  10.          }catch(InterruptedException e){  
  11.              e.printStackTrace();  
  12.          }  
  13.          System.out.println("Final amount="+ATM.m_acc.m_amount);   
  14.      }   
  15.      static class Account{   
  16.          int m_amount;   
  17.          String m_name;   
  18.          Account(int m,String name){   
  19.              m_amount=m;   
  20.              m_name  =name;   
  21.          }   
  22.          void Deposit(int m){   
  23.              try{   
  24.                  int a=m_amount;   
  25.                  a+=m;   
  26.                  Thread.sleep(10);   
  27.                  m_amount=a;   
  28.              }catch(InterruptedException e){   
  29.                  e.printStackTrace();   
  30.              }   
  31.          }   
  32.          void WithDraw(int m){   
  33.              try{   
  34.                  int a=m_amount;   
  35.                  a-=m;   
  36.                  Thread.sleep(10);   
  37.                  m_amount=a;   
  38.              }catch(InterruptedException e){   
  39.                  e.printStackTrace();   
  40.              }   
  41.          }   
  42.      }   
  43.      static class ATM extends Thread{   
  44.          static Account m_acc=new my.Account(10,"self");   
  45.          public void run(){   
  46.              m_acc.Deposit(1);   
  47.              m_acc.WithDraw(1);   
  48.          }   
  49.      }   
  50. }   
public class my{ 
     public static void main(String[] args){ 
         ATM[] pArr=new ATM[100]; 
         for(int i=0;i<pArr.length;++i){ 
             pArr[i]=new ATM(); 
             pArr[i].start(); 
         }
         try{
        	 Thread.sleep(300);
         }catch(InterruptedException e){
        	 e.printStackTrace();
         }
         System.out.println("Final amount="+ATM.m_acc.m_amount); 
     } 
     static class Account{ 
         int m_amount; 
         String m_name; 
         Account(int m,String name){ 
             m_amount=m; 
             m_name  =name; 
         } 
         void Deposit(int m){ 
             try{ 
                 int a=m_amount; 
                 a+=m; 
                 Thread.sleep(10); 
                 m_amount=a; 
             }catch(InterruptedException e){ 
                 e.printStackTrace(); 
             } 
         } 
         void WithDraw(int m){ 
             try{ 
                 int a=m_amount; 
                 a-=m; 
                 Thread.sleep(10); 
                 m_amount=a; 
             }catch(InterruptedException e){ 
                 e.printStackTrace(); 
             } 
         } 
     } 
     static class ATM extends Thread{ 
         static Account m_acc=new my.Account(10,"self"); 
         public void run(){ 
             m_acc.Deposit(1); 
             m_acc.WithDraw(1); 
         } 
     } 
} 

        要克服这个问题,就要为Deposit和WithDraw函数加上synchronized锁,但是这还不够,因为这只能放置多个同时存,或者多个同时取,不能方式同时存取造成的冲突。因此同步的对象应该是this指针。注意主函数里面要让所有的子线程调用join函数,这样主线程等待所有子线程完成才打印最终结果。

  1. //改进后的程序:   
  2. public class my{   
  3.      public static void main(String[] args){   
  4.          ATM[] pArr=new ATM[100];   
  5.          for(int i=0;i<pArr.length;++i){   
  6.              pArr[i]=new ATM();   
  7.              pArr[i].start();   
  8.          }  
  9.          try{  
  10.              for(int i=0;i<pArr.length;++i){  
  11.                  pArr[i].join();  
  12.              }  
  13.          }catch(InterruptedException e){  
  14.              e.printStackTrace();  
  15.          }  
  16.          System.out.println("Final amount="+ATM.m_acc.m_amount);   
  17.      }   
  18.      static class Account{   
  19.          int m_amount;   
  20.          String m_name;   
  21.          Account(int m,String name){   
  22.              m_amount=m;   
  23.              m_name  =name;   
  24.          }   
  25.          void Deposit(int m){   
  26.              try{   
  27.                  synchronized(this){  
  28.                      int a=m_amount;   
  29.                      a+=m;   
  30.                      Thread.sleep(10);   
  31.                      m_amount=a;   
  32.                  }  
  33.              }catch(InterruptedException e){   
  34.                  e.printStackTrace();   
  35.              }   
  36.          }   
  37.          synchronized void WithDraw(int m){   
  38.              try{   
  39.                  synchronized(this){  
  40.                      int a=m_amount;   
  41.                      a-=m;   
  42.                      Thread.sleep(10);   
  43.                      m_amount=a;   
  44.                  }  
  45.              }catch(InterruptedException e){   
  46.                  e.printStackTrace();   
  47.              }   
  48.          }   
  49.      }   
  50.      static class ATM extends Thread{   
  51.          static Account m_acc=new my.Account(10,"self");   
  52.          public void run(){   
  53.              m_acc.Deposit(1);   
  54.              m_acc.WithDraw(1);   
  55.          }   
  56.      }   
  57. }   
//改进后的程序:
public class my{ 
     public static void main(String[] args){ 
         ATM[] pArr=new ATM[100]; 
         for(int i=0;i<pArr.length;++i){ 
             pArr[i]=new ATM(); 
             pArr[i].start(); 
         }
         try{
	         for(int i=0;i<pArr.length;++i){
	        	 pArr[i].join();
	         }
         }catch(InterruptedException e){
        	 e.printStackTrace();
         }
         System.out.println("Final amount="+ATM.m_acc.m_amount); 
     } 
     static class Account{ 
         int m_amount; 
         String m_name; 
         Account(int m,String name){ 
             m_amount=m; 
             m_name  =name; 
         } 
         void Deposit(int m){ 
             try{ 
            	 synchronized(this){
            		 int a=m_amount; 
                     a+=m; 
                     Thread.sleep(10); 
                     m_amount=a; 
            	 }
             }catch(InterruptedException e){ 
                 e.printStackTrace(); 
             } 
         } 
         synchronized void WithDraw(int m){ 
             try{ 
            	 synchronized(this){
            		 int a=m_amount; 
                     a-=m; 
                     Thread.sleep(10); 
                     m_amount=a; 
            	 }
             }catch(InterruptedException e){ 
                 e.printStackTrace(); 
             } 
         } 
     } 
     static class ATM extends Thread{ 
         static Account m_acc=new my.Account(10,"self"); 
         public void run(){ 
             m_acc.Deposit(1); 
             m_acc.WithDraw(1); 
         } 
     } 
} 

        相比较而言,C++在C++11标准之前,线程同步依赖于操作系统的调用,非常麻烦,像posix系统就必须借助于Pthread线程库:

  1. #include <iostream>   
  2. #include <pthread.h>   
  3. #include <unistd.h>   
  4. using namespace std;  
  5. pthread_cond_t cond  =PTHREAD_COND_INITIALIZER;  
  6. pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;  
  7. void * start_routine(void* pvArg)  
  8. {  
  9.     char* pch=(char*)pvArg;  
  10.     pthread_mutex_lock(&mutex);  
  11.     pthread_cond_wait(&cond,&mutex);  
  12.     pthread_mutex_unlock(&mutex);  
  13.     cout << pch <<endl;  
  14.     cout.widen("jjjj");  
  15.     return NULL;  
  16. }  
  17.   
  18. int main()  
  19. {  
  20.     pthread_t thread;  
  21.     pthread_create(&thread,NULL,start_routine,(void*)"kkk");  
  22.     sleep(5);  
  23.     pthread_mutex_lock(&mutex);  
  24.     pthread_cond_signal(&cond);  
  25.     pthread_mutex_unlock(&mutex);  
  26.     pthread_cond_destroy(&cond);  
  27.     pthread_mutex_destroy(&mutex);  
  28.     pthread_join(thread,NULL);  
  29.     return 0;  
  30. }  
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
pthread_cond_t cond  =PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
void * start_routine(void* pvArg)
{
    char* pch=(char*)pvArg;
    pthread_mutex_lock(&mutex);
    pthread_cond_wait(&cond,&mutex);
    pthread_mutex_unlock(&mutex);
    cout << pch <<endl;
    cout.widen("jjjj");
    return NULL;
}

int main()
{
    pthread_t thread;
    pthread_create(&thread,NULL,start_routine,(void*)"kkk");
    sleep(5);
    pthread_mutex_lock(&mutex);
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    pthread_cond_destroy(&cond);
    pthread_mutex_destroy(&mutex);
    pthread_join(thread,NULL);
    return 0;
}

        而且Pthread里面的mutex和conditional还不是正交的,而windows下的mutex和event是正交的。C++11从boost里面引入了atom/thread库,情况终于有所改观。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1 目标检测的定义 目标检测(Object Detection)的任务是找出图像中所有感兴趣的目标(物体),确定它们的类别和位置,是计算机视觉领域的核心问题之一。由于各类物体有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具有挑战性的问题。 目标检测任务可分为两个关键的子任务,目标定位和目标分类。首先检测图像中目标的位置(目标定位),然后给出每个目标的具体类别(目标分类)。输出结果是一个边界框(称为Bounding-box,一般形式为(x1,y1,x2,y2),表示框的左上角坐标和右下角坐标),一个置信度分数(Confidence Score),表示边界框中是否包含检测对象的概率和各个类别的概率(首先得到类别概率,经过Softmax可得到类别标签)。 1.1 Two stage方法 目前主流的基于深度学习的目标检测算法主要分为两类:Two stage和One stage。Two stage方法将目标检测过程分为两个阶段。第一个阶段是 Region Proposal 生成阶段,主要用于生成潜在的目标候选框(Bounding-box proposals)。这个阶段通常使用卷积神经网络(CNN)从输入图像中提取特征,然后通过一些技巧(如选择性搜索)来生成候选框。第二个阶段是分类和位置精修阶段,将第一个阶段生成的候选框输入到另一个 CNN 中进行分类,并根据分类结果对候选框的位置进行微调。Two stage 方法的优点是准确度较高,缺点是速度相对较慢。 常见Tow stage目标检测算法有:R-CNN系列、SPPNet等。 1.2 One stage方法 One stage方法直接利用模型提取特征值,并利用这些特征值进行目标的分类和定位,不需要生成Region Proposal。这种方法的优点是速度快,因为省略了Region Proposal生成的过程。One stage方法的缺点是准确度相对较低,因为它没有对潜在的目标进行预先筛选。 常见的One stage目标检测算法有:YOLO系列、SSD系列和RetinaNet等。 2 常见名词解释 2.1 NMS(Non-Maximum Suppression) 目标检测模型一般会给出目标的多个预测边界框,对成百上千的预测边界框都进行调整肯定是不可行的,需要对这些结果先进行一个大体的挑选。NMS称为非极大值抑制,作用是从众多预测边界框中挑选出最具代表性的结果,这样可以加快算法效率,其主要流程如下: 设定一个置信度分数阈值,将置信度分数小于阈值的直接过滤掉 将剩下框的置信度分数从大到小排序,选中值最大的框 遍历其余的框,如果和当前框的重叠面积(IOU)大于设定的阈值(一般为0.7),就将框删除(超过设定阈值,认为两个框的里面的物体属于同一个类别) 从未处理的框中继续选一个置信度分数最大的,重复上述过程,直至所有框处理完毕 2.2 IoU(Intersection over Union) 定义了两个边界框的重叠度,当预测边界框和真实边界框差异很小时,或重叠度很大时,表示模型产生的预测边界框很准确。边界框A、B的IOU计算公式为: 2.3 mAP(mean Average Precision) mAP即均值平均精度,是评估目标检测模型效果的最重要指标,这个值介于0到1之间,且越大越好。mAP是AP(Average Precision)的平均值,那么首先需要了解AP的概念。想要了解AP的概念,还要首先了解目标检测中Precision和Recall的概念。 首先我们设置置信度阈值(Confidence Threshold)和IoU阈值(一般设置为0.5,也会衡量0.75以及0.9的mAP值): 当一个预测边界框被认为是True Positive(TP)时,需要同时满足下面三个条件: Confidence Score > Confidence Threshold 预测类别匹配真实值(Ground truth)的类别 预测边界框的IoU大于设定的IoU阈值 不满足条件2或条件3,则认为是False Positive(FP)。当对应同一个真值有多个预测结果时,只有最高置信度分数的预测结果被认为是True Positive,其余被认为是False Positive。 Precision和Recall的概念如下图所示: Precision表示TP与预测边界框数量的比值 Recall表示TP与真实边界框数量的比值 改变不同的置信度阈值,可以获得多组Precision和Recall,Recall放X轴,Precision放Y轴,可以画出一个Precision-Recall曲线,简称P-R
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值