先来看看一般的多线程共用一个资源的情况:
程序输出结果为:
the workID of threadonefun is:12
the workID of threadtwo is 12
the workID of threadonefun is:14
the workID of threadtwo is 14
the workID of threadonefun is:16
the workID of threadtwo is 16
the workID of threadonefun is:18
the workID of threadtwo is 18
the workID of threadonefun is:20
the workID of threadtwo is 20
.....
线程1和线程2输出的数一样,显然与预计的结果不符(预计输出结果为从10到100顺序输出)
下面来看看互斥对象方法来解决线程同步问题:
输出结果为:
the work id of thread one is:11
the work id of thread two is:12
the work id of thread one is:13
the work id of thread two is:14
the work id of thread one is:15
the work id of thread two is:16
the work id of thread one is:17
the work id of thread two is:18
......
线程1和线程2明显实现了同步共享资源。
下面来看看临界区实现线程同步使用公共资源:
程序输出结果为:
the thread two of workid is:11
the thread one of workID is:12
the thread two of workid is:13
the thread one of workID is:14
the thread two of workid is:15
the thread one of workID is:16
the thread two of workid is:17
the thread one of workID is:18
.....
依然能够实现多线程使用公共资源。
再来看看事件实现线程同步:
程序输出结果为:
the workID of threadone is:11
the workID of threadone is:12
the workID of threadtwo is:13
the workID of threadone is:14
the workID of threadtwo is:15
the workID of threadone is:16
the workID of threadtwo is:17
the workID of threadone is:18
the workID of threadtwo is:19
the workID of threadone is:20
......
也实现了线程同步机制。
对于以上3种线程同步机制的内部原理,我也不能说的很清楚,书上只是说了个大概,云里雾里的,估计要等到以后看《windows核心编程》的时候才能给出适当解释,在这里,我暂时先把互斥对象方法理解为:系统创建了一个容器MUTEX,这个容器里每次只能装多个线程中的一个共享资源,且只能将这个资源供给一个线程使用,如果多个线程同时访问它的话,就按先来先使用的方法排队等待,直到使用这个共享资源的东西释放了它。
对临界区的理解也类似:对于临界区部分内的资源,如果多个线程共享的话,按先来先使用的方法来使用,每次只能供一个线程使用。
对事件的理解也类似:多个线程共同使用一个事件对象,当多个线程内有共享资源时,按先来先使用(资源)的方法,每次只能供一个线程使用。