Computer 기타
Pthread with Semaphore <posix>
JaeYoung
2010. 3. 16. 00:11
아래 Mutex로 동기화 했던걸 Semaphore로 변형 시킨거
위에껀 이름있는 세마포어???
어래껀 익명 세미포어
#include#include #include #include #include //for O_CREAT #include using namespace std; sem_t *mysem; struct arg { int start; int end; int time; string name; }; void *cnt(void* a) { struct arg* temp=(struct arg*)a; for(int i= temp->start; i < temp->end;i++) { sem_wait(mysem); cout << temp->name <<" : " << i << endl; sem_post(mysem); sleep(temp->time); } pthread_exit(NULL); } int main() { pthread_t td1,td2,td3; struct arg ar1,ar2,ar3; void* state; ar1.start=0; ar1.end=20; ar1.name=string("thread1"); ar1.time=1; ar2.start=-10; ar2.end=0; ar2.name=string("thread2"); ar2.time=2; ar3.start=100; ar3.end=110; ar3.name=string("thread3"); ar3.time=3; sem_unlink("mysem"); //세마포어 삭제 if((mysem = sem_open("mysem", O_CREAT, 0777, 1)) == NULL) // /dev/shm에 해당이름의 세마포어 파일로 생성됨. // O_CREAT : 파일이 존재하면 따로 생성하지 않음 , 0777 퍼미션 { perror("Sem Open Error"); return 1; } pthread_create(&td1,NULL,cnt,(void*)&ar1); pthread_create(&td2,NULL,cnt,(void*)&ar2); pthread_create(&td3,NULL,cnt,(void*)&ar3); pthread_join(td1,&state); pthread_join(td2,&state); pthread_join(td3,&state); return 0; }
#include#include #include #include #include using namespace std; sem_t mysem; struct arg { int start; int end; int time; string name; }; void *cnt(void* a) { struct arg* temp=(struct arg*)a; for(int i= temp->start; i < temp->end;i++) { sem_wait(&mysem); cout << temp->name <<" : " << i << endl; sem_post(&mysem); sleep(temp->time); } pthread_exit(NULL); } int main() { pthread_t td1,td2,td3; struct arg ar1,ar2,ar3; void* state; ar1.start=0; ar1.end=20; ar1.name=string("thread1"); ar1.time=1; ar2.start=-10; ar2.end=0; ar2.name=string("thread2"); ar2.time=2; ar3.start=100; ar3.end=110; ar3.name=string("thread3"); ar3.time=3; if(sem_init(&mysem,0,1) ==-1) { cerr <<"Error"; exit(0); } pthread_create(&td1,NULL,cnt,(void*)&ar1); pthread_create(&td2,NULL,cnt,(void*)&ar2); pthread_create(&td3,NULL,cnt,(void*)&ar3); pthread_join(td1,&state); pthread_join(td2,&state); pthread_join(td3,&state); return 0; }