//main.cpp
#include <iostream>
#include <semaphore.h>
#include <pthread.h>
#include <string.h>
#include <signal.h>
#include <stdlib.h>
#define _SIZE_ 10
using namespace std;
void EXIT(int arg)//注册信号处理函数。
{
cout<<"Come Over!"<<endl;
exit(0);
}
class sem
{
public:
sem(int Default = _SIZE_)
{
start = 0;
end = 0;
sem_init(&empty_size,0,0);
sem_init(&exit_size,Default,0);
}
void SetStr(string s)
{
sem_post(&exit_size);
str[end]=s;
end = (end+1)%_SIZE_;
sem_wait(&empty_size);
}
string GetStr()
{
string s;
sem_wait(&exit_size);
s = str[start];
start = (start+1)%_SIZE_;
sem_post(&empty_size);
return s;
}
~sem()
{
sem_destroy(&empty_size);
sem_destroy(&exit_size);
}
private:
int start;
int end;
string str[_SIZE_];
sem_t empty_size;
sem_t exit_size;
};
void* Write(void *arg)
{
sem *sm = (sem *)arg;
while(1)
{
sm->SetStr("this is semaphore message!!");
sleep(1);//让线程写的速度慢于线程读的速度,可以
//看到互斥等待访问并不影响正常的需求。
}
return (void*) 0;
}
void* Read(void *arg)
{
sem *sm = (sem *)arg;
while(1)
{
cout<<sm->GetStr().c_str()<<endl;
}
return (void*) 0;
}
int main()
{
sem sm;
pthread_t idone,idtwe;
signal(SIGINT,EXIT);//遇到2号信号SIGINT作出相应的处理。
pthread_create(&idone,NULL,Write,&sm);
pthread_create(&idtwe,NULL,Read,&sm);
pthread_join(idone,NULL);
pthread_join(idtwe,NULL);
return 0;
}
//下面是Makefile
OUT=a.out
MAINCPP=main.cpp
MAINO=main.o
CC=g++
LIB=-lpthread
$(OUT):$(MAINO)
@$(CC) -o [email protected] $^ $(LIB)
$(MAINO):$(MAINCPP)
@$(CC) -c $<
.PHONY:clean
clean:
rm -rf $(OUT) $(MIANO)
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-10 12:29:43