根据信号量的原理,自己写了一个简单的信号量类,用于线程同步,以下代码在Linux下调试通过
#include
#include
#include
using namespace std;
class Sem
{
public:
Sem(int &initValue){ semValue = initValue;}
void WaitSem()
{
//信号量大于0,将信号量减1
if(semValue > 0)
{
semValue--;
}
else
{
//信号量 <= 0,则阻塞线程,直到信号量大于0
while(1)
{
if(semValue > 0)
{
semValue--;
break;
}
else
continue;
}
}
}
void PostSem()
{ //信号量加1
semValue++;
}
private:
int semValue;
};
int semp =0; //信号量初始值
Sem sem(semp);
int ncount = 0;
int threadnum = 0;
void *count1(void* arg)
{
sem.WaitSem();
threadnum++;
char name[20];
sprintf(name, "thread %d", threadnum);
cout << name << " start!" << endl;
for(int i = 0; i < 5; i++)
{
ncount += 3;
}
sleep(1);
cout << name << " ncount: " << ncount << endl;
sem.PostSem();
return (void*)0;
}
int main()
{
pthread_t tid[10];
cout << "start create thread!" << endl;
sem.PostSem();
for(int i = 0; i < 10; i++)
{
pthread_create(&tid[i], NULL, count1, NULL);
}
for(int i = 0; i < 10; i++)
{
pthread_join(tid[i], NULL);
}
sleep(2);
cout << "main thread" << endl;
return 0;
}
程序的运行结果如下
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
此信号量类实现了简单的线程同步