多线程编程——几种线程同步机制

先来看看一般的多线程共用一个资源的情况:

 

 

 

程序输出结果为:

 

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,这个容器里每次只能装多个线程中的一个共享资源,且只能将这个资源供给一个线程使用,如果多个线程同时访问它的话,就按先来先使用的方法排队等待,直到使用这个共享资源的东西释放了它。

对临界区的理解也类似:对于临界区部分内的资源,如果多个线程共享的话,按先来先使用的方法来使用,每次只能供一个线程使用。

对事件的理解也类似:多个线程共同使用一个事件对象,当多个线程内有共享资源时,按先来先使用(资源)的方法,每次只能供一个线程使用。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值