42의 철학자 과제를 해결하기 위해 기반 지식을 정리하였다.
위의 링크와 같이 유명한 철학자 문제를 시뮬레이션하는 과제이다.
과제는 3가지의 유형을 해결하도록 제시한다.
각각의 철학자는 포크를 하나씩 가지고 있으며 두 개의 포크를 집어야만 식사를 할 수 있다.
첫번째 유형은 포크를 각각의 철학자가 가지고 있다.
나머지 2가지의 유형은 식탁의 중앙에 포크를 두고 철학자가 각자 집어간다.
아래에 정리한 함수를 활용하여 식사, 잠자기, 생각과 같은 행동을 하는 철학자를 만들 수 있다.
#include <unistd.h>
int usleep(useconds_t microseconds);
#include <sys/time.h>
int gettimeofday(struct timeval *tv, struct timezone *tz);
struct timeval {
time_t tv_sec; /* seconds since Jan. 1, 1970 */
suseconds_t tv_usec; /* and microseconds */
};
gettimeofday(&startTime, NULL);
// 특정 작업 수행
sleep(1);
gettimeofday(&endTime, NULL);
diffTime = ( endTime.tv_sec - startTime.tv_sec ) + ( endTime.tv_usec - startTime.tv_usec );
#include <pthread.h>
int pthread_create(pthread_t *thread, const pthread_attr_t *attr, void *(*start_routine) (void *), void *arg);
struct thread_info { /* Used as argument to thread_start() */
pthread_t thread_id; /* ID returned by pthread_create() */
int thread_num; /* Application-defined thread # */
char *argv_string; /* From command-line argument */
};
struct thread_info tinfo;
int th_result;
th_result = pthread_create(&(tinfo.thread_id), NULL, t_function, (void *)&tinfo);
#include <pthread.h>
int pthread_detach(pthread_t th);
#include <pthread.h>
int pthread_join(pthread_t th, void **thread_return);
#include <pthread.h>
int pthread_mutex_init(pthread_mutex_t * mutex, const pthread_mutex_attr *attr);
pthread_mutex_t mutex_lock; // 전역 변수로 사용해야 다른 스레드 함수에서 접근 가능할 듯
void *t_function()
{
pthread_mutex_lock(&mutex_lock);
// critical section
pthread_mutex_unlock(&mutex_lock);
}
pthread_mutex_init(&mutex_lock, NULL);
#include <pthread.h>
int pthread_mutex_destroy(pthread_mutex_t *mutex);
#include <pthread.h>
int pthread_mutex_lock(pthread_mutex_t *mutex);
#include <pthread.h>
int pthread_mutex_unlock(pthread_mutex_t *mutex);
/dev/sem
경로에 생성된다:#include <fcntl.h> /* For O_* constants */
#include <sys/stat.h> /* For mode constants */
#include <semaphore.h>
sem_t *sem_open(const char *name, int oflag);
sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);
set_t *sem;
sem = sem_open(SEM_NAME, O_CREAT, 0664, 1);
if (sem == SEM_FAILED)
sem_unlink(SEM_NAME);
#include <semaphore.h>
int sem_close(sem_t *sem);
#include <semaphore.h>
int sem_post(sem_t *sem);
sem_t sem;
sem_post(&sem);
#include <semaphore.h>
int sem_wait(sem_t *sem);
#include <semaphore.h>
int sem_unlink(const char *name);