콘텐츠로 바로가기

now0930 일지

이런저런 생각

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

mutex 예제

linux system programming, 238p. 두 시간 삽질했다. thread arg 를 포인터로 주는데 여러 개를 쓰려면 struct로 정의해서 써야 한댄다. 맞는지 틀린지..

#include <pthread.h>
#include <stdio.h>
#include <unistd.h>


//arg를 여러 파라미터로 사용하기 위해,
//구조체로 정의
//https://stackoverflow.com/questions/52812004/parameter-passing-multiple-values-using-void-pointer
//여기 참조
//공유 자원.
int sharedInt=0;
//mutex 설정.
static pthread_mutex_t the_mutex = PTHREAD_MUTEX_INITIALIZER;

struct myStruct {
	//struct는 initilizer를 지원하지 않음.
	char *message;
	int index;
	//index를 보고 입력된 파라미터로 hello, one, two, three를 선택.
	//이렇게 구현하려 했으나, 힘들어 문자열로 변경.
	//index로 sharedInt를 업데이트 하려 했으나,
	//잘 안됨..
	//스레드가 시작할 때마다 sharedInt를 업데이트 하면 기존 값을
	//버리고 다시 씀!!
	//thread 안에서만 공유 자원을 조작..


};



void* start_routine(void* arg ){
	int pid;
	int threadID;
	//struct로 arg를 받기 위해, 
	//struct로 변경.
	struct myStruct *temp;

	temp = arg;
	//pointer 로 global 변수 변경

	//pthread_mutex_lock(&the_mutex);
	//sharedInt = temp->index;

	//printf("my thread sentence is \"%s\"\n", temp->message);
	//printf("temp->index is %d\n", temp->index);

	pthread_mutex_lock(&the_mutex);

	printf("SharedInt는 %d\n",sharedInt);
	if(sharedInt == 0){
		//strsep(temp->message, " ");
		//printf("my thread word is %s\n",outputword);
		printf("zero\n");
		//temp->index++;

	}

	else if(sharedInt == 1){
		//printf("my thread word is %s\n",outputword);
		printf("one\n");
		//temp->index++;

	}
	else if(sharedInt == 2){
		printf("two\n");
		//temp->index++;

	}

	else{
		printf("three or more\n");
	}
	sharedInt++;

	pthread_mutex_unlock(&the_mutex);

	}

int main(){

	pthread_t thread[2];
	int ret, errorno;
	struct myStruct message = {"hello one two three", 0 };
	printf("myStruct message index는 %d\n", message.index);
	//아래 부분은 불필요 부분. thread 밖에서 조작하여 무의미함.
	//message.index=2;

	ret = pthread_create(&thread[0],NULL,start_routine,(void*)&message);

	if(ret<0){
		errorno = ret;
		//printf("%d\n",errorno);
		perror("pthread_create");
		return -1;
	}
	//아래 부분은 불필요 부분. thread 밖에서 조작하여 무의미함.
	//message.index=1;

	//printf("myStruct message index는 %d\n", message.index);

	//printf("struct 출력: %d",message.index);
	//printf("message 확인 %d",message.index);

	ret = pthread_create(&thread[1],NULL,start_routine,(void*)&message);

	if(ret<0){
		errorno = ret;
		//printf("%d\n",errorno);
		perror("pthread_create");
		return -1;
	}

	//각 스레드 끝나길 대기

	pthread_join(thread[0],NULL);
	pthread_join(thread[1],NULL);
	//mutex 삭제
	pthread_mutex_destroy(&the_mutex);
	printf("completed\n");
	return 0;

}

100번 돌리면 mutex lock을 설정한 경우와 설정하지 않은 경우 값이 다름. 나름 이해했다고 믿고 싶다.

이 글 공유하기:

  • Tweet
발행일 2020-06-29글쓴이 이대원
카테고리 생활코딩 태그 c, linux, system program

댓글 남기기응답 취소

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

글 내비게이션

이전 글

thread 예제

다음 글

신과 함께 rss

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로 제작.