13Day Study
[[[[[POSIX 쓰레드(Thread)]]]]]
Native POSION Thread Library(NPTL)를 사용
기본값
#include < pthread.h>
int pthread_create(pthread_t *thread, pthread_attr_t *attr, void *(*start_routine)(void *), void *arg); => 스레드 생성
void pthread_exit(void *retval); => 스레드 종료
int pthread_join(pthread_t th, void **thread_return); => wait 기능
스레드 예:
#include < stdio.h>
#include < unistd.h>
#include < stdlib.h>
#include < pthread.h>
void *thread_function(void *arg);
char message[] = "Hello World";
int main() {
int res;
pthread_t a_thread;
void *thread_result;
res=pthread_create(&a_thread, NULL, thread_function, (void *)message);
if(res != 0) {
perror("Thread creation failed");
exit(EXIT_FAILURE);
}
printf("Waiting for thread to finish...\n");
res=pthread_join(a_thread, &thread_result);
if(res != 0) {
perror("Thread join failed");
exit(EXIT_FAILURE);
}
printf("Thread joined, it returned %s\n", (char *)thread_result);
printf("Message is now %s\n",message);
exit(EXIT_SUCCESS);
}
void *thread_function(void *arg) {
printf("thread_function is running. Argument was %s\n", (char *)arg);
sleep(3);
strcpy(message, "Bye!");
pthread_exit("Thank you for the CPU time");
}
[root@waf cstudy]# ./thread
Waiting for thread to finish...
thread_function is running. Argument was Hello World
Thread joined, it returned Thank you for the CPU time
Message is now Bye!
스레드 최대 갯수 세는 프로그램 예:
#include < stdio.h>
#include < pthread.h>
#include < stdlib.h>
#include < unistd.h>
unsigned int total=0;
unsigned int threadcount=0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void update_size( unsigned size) {
}
void *threadFunc(void *arg) {
int tnum = (int) arg;
// add our thread number to the total
pthread_mutex_lock(&m);
total += tnum;
threadcount--;
printf("I am thread %d, and I am done!\n",tnum);
pthread_mutex_unlock(&m);
return(NULL);
}
int main(int argc, char **argv) {
int i,n;
pthread_t tid;
if (argc!=2) {
fprintf(stderr,"Error - I need the number of threads!\n");
exit(1);
}
n = atoi(argv[1]);
if (n< =0) {
fprintf(stderr,"Give me a number greater than 0\n");
exit(1);
}
for (i=1;i< =n;i++) {
threadcount++;
if (pthread_create(&tid,NULL,threadFunc,(void *)i)) {
fprintf(stderr,"Error creating thread number %d\n",i);
}
}
while (threadcount);
printf("total is %d\n",total);
return(0);
}
동기화(synchronization)
뮤텍스와 세마포 둘 다 공유자원의 크리티컬 섹션 문제를 해결하는 방법이다.
뮤텍스는 공유자원에 접근할 수 있는 열쇠라고 보면 된다.
열쇠가 있는 녀석만이 공유자원에 접근할 수 있는 것이다.
이렇게 해서 크리티컬 섹션 문제를 해결한다.
그럼 세마포는?
세마포는 뮤텍스보다 더 범용적으로 쓰일 수 있다.
왜? 세마포는 공유자원의 접근에 대한 한계값(n)을 부여하고
n보다 작으면 프로세스가 공유자원에 접근할 수 있다.
그럼 뮤텍스와 세마포의 차이점은???
세마포를 뮤텍스와 똑같은 기능을 하게 할 수 있다.
그것이 바로 바이너리세마포 이다.
바이너리... 말 그대로 0과 1 둘 밖에 없다.
즉 0이면 못하는 거고 1이면 접근 가능하다.
이러면 세마포와 뮤텍스의 기능이 같아진다.
#include < semaphore.h>
int sem_init(sem_t *sem, int pshared, unsigned int value);
int sem_wait(sem_t *sem);
int sem_post(sem_t *sem);
int sem_destory(sem_t *sem);
세마포어를 이용하여 쓰레드가 작업을 완료할 때까지 메인 쓰레드가 기다리도록 만들 수 있음
뮤텍스
#include < pthread.h>
pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
pthread_mutex_lock(pthread_mutex_t *mutex);
pthread_mutex_unlock(pthread_mutex_t *mutex);
pthread_mutex_destroy(pthread_mutex_t *mutex);
P.S 책이 넘 후졌다... 인터넷으로 따로 공부하자
2009년 3월 13일 금요일
피드 구독하기:
댓글 (Atom)
댓글 없음:
댓글 쓰기