콘텐츠로 바로가기

now0930 일지

이런저런 생각

  • 홈
  • 비공개
  • 강좌
  • 잔여 작업 조회
  • 위치

memory based semaphore, unix network programming p241

이름있는 세마포어 말고 메모리에 올려 사용하는 방법도 있다. 책은 sem_init(…, 두번째 arg,…)에서 두번째 입력하는 숫자를 thread에서 공유할 거면 0, 프로세스간 할거면 1로 하라고 한다. 1로 하여 thread도 잘 된다.

named semaphore는 포인터를 선언했고 파일에 영역을 만들었다. 이와 다르게 직접 데이터를 선언하고 주소로 넘겨줘야 한다.

ipcs로 보일 법 한데, 안 보인다. 무엇이 잘못되었는지 모르겠다.

/* include main */
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <semaphore.h>
#include <sys/stat.h>
#include <unistd.h>
#define	NBUFF	 10
#define	SEM_MUTEX	"mutex"	 	/* these are args to px_ipc_name() */
#define	SEM_NEMPTY	"empty"
#define	SEM_NSTORED	"nstored"

int		nitems;					/* read-only by producer and consumer */
struct {	/* data shared by producer and consumer */
  int	buff[NBUFF];
  //포인터 대신 세마포어로 변경.
  //sem_t	*mutex, *nempty, *nstored;
  sem_t	mutex, nempty, nstored;		/* semaphores, not pointers */

} shared;

void	*produce(void *), *consume(void *);

int
main(int argc, char **argv)
{
	pthread_t	tid_produce, tid_consume;

	if (argc != 2)
		perror("usage: prodcons1 <#items>");
	nitems = atoi(argv[1]);
		/* 4create three semaphores */
	//memory based로 변경.
	/*
	shared.mutex = sem_open(SEM_MUTEX, O_CREAT | O_EXCL,
							0660, 1);
	shared.nempty = sem_open(SEM_NEMPTY, O_CREAT | O_EXCL,
							 0660, NBUFF);
	shared.nstored = sem_open(SEM_NSTORED, O_CREAT | O_EXCL,
							  0660, 0);
							  */


	//두번째 파라미터를 0으로 설정해야 thread간 전달.
	//sem_init(&shared.mutex, 1, 1) 설정해도 잘 됨..

	sem_init(&shared.mutex, 0, 1);
	sem_init(&shared.nempty, 0, NBUFF);
	sem_init(&shared.nstored, 0, 0);


		/* 4create one producer thread and one consumer thread */
	//pthread_setconcurrency(2);
	//pthread_setconcurrency();
	pthread_create(&tid_produce, NULL, produce, NULL);
	pthread_create(&tid_consume, NULL, consume, NULL);

		/* 4wait for the two threads */
	pthread_join(tid_produce, NULL);
	pthread_join(tid_consume, NULL);

		/* 4remove the semaphores */
	//메모리 베이스로 변경.
	/*
	sem_unlink(SEM_MUTEX);
	sem_unlink(SEM_NEMPTY);
	sem_unlink(SEM_NSTORED);
	*/


	//ipcs로 확인하기위해 대기
	sleep(10);

	sem_destroy(&shared.mutex);
	sem_destroy(&shared.nempty);
	sem_destroy(&shared.nstored);

	exit(0);
}
/* end main */

/* include prodcons */
void *
produce(void *arg)
{
	int		i;

	for (i = 0; i < nitems; i++) {

		sem_wait(&shared.nempty);	/* wait for at least 1 empty slot */
		sem_wait(&shared.mutex);

		shared.buff[i % NBUFF] = i;	/* store i into circular buffer */
		sem_post(&shared.mutex);
		sem_post(&shared.nstored);	/* 1 more stored item */


	}
	return(NULL);
}

void *
consume(void *arg)
{
	int		i;
	int tmpnempty, tmpmutex, tmpnstored;

	for (i = 0; i < nitems; i++) {


		sem_wait(&shared.nstored);		/* wait for at least 1 stored item */
		sem_wait(&shared.mutex);


		if (shared.buff[i % NBUFF] = i)
			printf("buff[%d] = %d\n", i, shared.buff[i % NBUFF]);
		sem_post(&shared.mutex);
		sem_post(&shared.nempty);		/* 1 more empty slot */

	}
	return(NULL);
}
/* end prodcons */
pi@raspberrypi:~/Project/cCode/IPC $ ipcs

------ Message Queues --------
key        msqid      owner      perms      used-bytes   messages    

------ Shared Memory Segments --------
key        shmid      owner      perms      bytes      nattch     status      

------ Semaphore Arrays --------
key        semid      owner      perms      nsems     

ipcs는 system V 기능이라 posix semaphore는 해당하지 않는다. 보이지 않음이 당연하다.

이 글 공유하기:

  • Tweet
발행일 2020-07-17글쓴이 이대원
카테고리 생활코딩 태그 c, linux, network program, pthread, semaphore

댓글 남기기응답 취소

이 사이트는 Akismet을 사용하여 스팸을 줄입니다. 댓글 데이터가 어떻게 처리되는지 알아보세요.

글 내비게이션

이전 글

unix network programming, vol 2

다음 글

다른 process간 named semaphore 사용(실패)

2025 5월
일 월 화 수 목 금 토
 123
45678910
11121314151617
18192021222324
25262728293031
4월    

최신 글

  • common mode, differential mode 2025-05-11
  • signal conditioner, 신호 처리기 2025-05-10
  • strain gage 2025-05-09
  • 칼만 필터 2025-05-01
  • positioner(I/P) 2025-04-26

카테고리

  • 산업계측제어기술사
  • 삶 자국
    • 책과 영화
    • 투자
  • 생활코딩
    • LEGO
    • ROS
    • tensorflow
  • 전기기사
  • 피아노 악보

메타

  • 로그인
  • 엔트리 피드
  • 댓글 피드
  • WordPress.org

페이지

  • 소개
  • 잔여 작업 조회
    • 작업 추가
    • 작업의 사진 조회
    • 작업 수정 페이지
  • 사진
    • GPS 입력된 사진
    • 사진 조회
  • 위치
    • 하기 휴가 방문지
    • 해외 출장

태그

android bash c docker driver FSM gps java kernel LEGO linux mysql network program opcua open62541 plc programmers python raspberry reinforcementLearning ros state space system program tensorflow transfer function 경제 미국 민수 삼국지 세계사 실기 에너지 역사 유전자 일본 임베디드 리눅스 전기기사 조선 중국 채윤 코딩 테스트 통계 한국사 한국어

팔로우하세요

  • Facebook
now0930 일지
WordPress로 제작.