2013년 1월 26일 토요일

헤드 퍼스트 C 12강 (thread)


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <pthread.h> //포직스 스레드 라이브러리 사용

void error(char* msg)
{
fprintf(stderr, "%s: %s\n", msg, strerror(errno));
exit(1);
}

void* does_not(void *a)
{
int i = 0;
for (i = 0; i < 5; i++) {
sleep(1);
puts("Does not!");
}
return NULL;
}

void* does_too(void *a)
{
int i = 0;
for (i = 0; i < 5; i++) {
sleep(1);
puts("Does too!");
}
return NULL;
}

int main()
{
pthread_t t0;
pthread_t t1;
if (pthread_create(&t0, NULL, does_not, NULL) == -1)
error("t0 스레드를 생성할 수 없습니다.");
if (pthread_create(&t1, NULL, does_too, NULL) == -1)
error("t1 스레드를 생성할 수 없습니다.");

void* result;
if (pthread_join(t0, &result) == -1)
error("t0 스레드를 종료할 수 없습니다.");
if (pthread_join(t1, &result) == -1)
error("t1 스레드를 종료할 수 없습니다.");

return 0;
}

------------------ 이 코드는 스레드가 충동하는 문제가 있음 -----------

댓글 없음:

댓글 쓰기