[PR]上記の広告は3ヶ月以上新規記事投稿のないブログに表示されています。新しい記事を書く事で広告が消えます。
#include <iostream> #include <sys/shm.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/time.h> typedef int semaphore; const int N = 10; semaphore *mutex; semaphore *empty; semaphore *full; int *store; void down(std::string s, semaphore &sem) { while (sem <= 0) ; sem--; std::cout << s << sem << std::endl; fflush(stdout); } void up (std::string s, semaphore &sem) { sem++; std::cout << s << sem << std::endl; fflush(stdout); } void producer(void) { while(true){ std::cout << "--- producer start ---" << std::endl; down("p empty ", *empty); down("p mutex ", *mutex); // insert_item store[(int)*full] = 1; std::cout << "p store: "; for (int i=0; i<N; i++) std::cout << store[i] << " "; std::cout << std::endl; up ("p mutex ", *mutex); up ("p full ", *full); sleep(1); std::cout << "--- producer end ---" << std::endl; fflush(stdout); } } void consumer(void) { while(true){ std::cout << "--- consumer start ---" << std::endl; down("c full ", *full); down("c mutex ", *mutex); // remove_item store[(int)*full] = 0; std::cout << "c store: "; for (int i=0; i<N; i++) std::cout << store[i] << " "; std::cout << std::endl; up ("c mutex ", *mutex); up ("c empty ", *empty); sleep(1); std::cout << "--- consumer end ---" << std::endl; fflush(stdout); } } int main (int argc, char* argv[]) { const int segment1 = shmget(IPC_PRIVATE, 1, S_IRUSR|S_IWUSR); mutex = (semaphore*)shmat(segment1, NULL, 0); *mutex = 1; const int segment2 = shmget(IPC_PRIVATE, 1, S_IRUSR|S_IWUSR); empty = (semaphore*)shmat(segment2, NULL, 0); *empty = N; const int segment3 = shmget(IPC_PRIVATE, 1, S_IRUSR|S_IWUSR); full = (semaphore*)shmat(segment3, NULL, 0); *full = 0; const int segment4 = shmget(IPC_PRIVATE, N, S_IRUSR|S_IWUSR); store = (semaphore*)shmat(segment4, NULL, 0); for (int i=0; i<N; i++) store[i] = 0; const pid_t pid = fork(); std::cout << "pid : " << pid << std::endl; fflush(stdout); if (pid == 0) { consumer(); } else { producer(); } shmctl (segment1, IPC_RMID, NULL); shmctl (segment2, IPC_RMID, NULL); shmctl (segment3, IPC_RMID, NULL); shmctl (segment4, IPC_RMID, NULL); return 0; }