游戏开发,系统架构; 博客迁移到:http://www.jianshu.com/u/3ac0504b3b8c
全部博文(198)
分类: LINUX
2011-08-26 09:45:31
程序的运行结果如下
start create thread!
thread 1 start!
thread 1 ncount: 15
thread 2 start!
thread 2 ncount: 30
thread 3 start!
thread 3 ncount: 45
thread 4 start!
thread 4 ncount: 60
thread 5 start!
thread 5 ncount: 75
thread 6 start!
thread 6 ncount: 90
thread 7 start!
thread 7 ncount: 105
thread 8 start!
thread 8 ncount: 120
thread 9 start!
thread 9 ncount: 135
thread 10 start!
thread 10 ncount: 150
main thread
在一个线程对ncount进行操作的时候,其他线程被阻塞,因此打印出来的ncount依次累加15.
注释掉 sem.WaitSem()和sem.PostSem()之后,程序运行结果如下
start create thread!
thread 1 start!
thread 2 start!
thread 3 start!
thread 4 start!
thread 5 start!
thread 6 start!
thread 7 start!
thread 8 start!
thread 9 start!
thread 10 start!
thread 1 ncount: 150
thread 2 ncount: 150
thread 3 ncount: 150
thread 4 ncount: 150
thread 5 ncount: 150
thread 6 ncount: 150
thread 7 ncount: 150
thread 8 ncount: 150
thread 9 ncount: 150
thread 10 ncount: 150
main thread
因为在1秒钟里,10个线程都对ncount加了15,因此大于出来的ncount为150
此信号量类实现了简单的线程同步