

| segment | 내용 |
|---|---|
| text | 코드 |
| data | 초기값이 할당된 변수 |
| bss | 초기값이 할당되지 않은 변수 |
| stack | 지역 변수 |
| heap | malloc으로 만든 변수 (동적 변수) |
int t;
int g = 32;
int main(){
int q = 31;
int *p = (int*)malloc(4);
}

| 변수 | segment | 이유 |
|---|---|---|
| t | .bss | 초기값이 없는 전역 변수 |
| g | .data | 초기값이 있는 전역 변수 |
| q | .stack | main 안의 지역 변수 |
| p | .stack | 포인터 변수도 지역 변수 |
| malloc(4) | .heap | malloc으로 동적 할당한 공간 |
-> p 자체는 stack에 있고, p가 가리키는 malloc(4) 공간이 heap에 만들어진다.
| API | 기능 |
|---|---|
#include <pthread.h> | POSIX thread 헤더 (위치: /usr/include/pthread.h) |
pthread_t | Thread 핸들러, 값은 pthread_create()가 채워 넣음 |
pthread_create(&t, NULL, 함수, 파라미터) | Thread 생성 후 함수 실행 |
pthread_join(t, NULL) | Thread 종료를 기다리고 자원 정리 |
gcc sample.c -o ./gogo -lpthread | pthread 라이브러리를 같이 링킹 |
| 매개변수 | 타입 | 설명 |
|---|---|---|
| thread id | pthread_t* | Thread 핸들러 주소 |
| thread 속성 | const pthread_attr_t* | 우선순위 등 설정, 이식성 문제로 보통 NULL |
| 함수 | void* (*)(void*) | Thread로 동작시킬 함수의 주소 (함수 포인터) |
| 파라미터 | void* | Thread 함수에 전달할 인자 값 |
void*를 리턴하는 형태로 작성하고, 돌려줄 값이 없으면 return NULL;함수로 호출하면 abc()의 무한 반복 때문에 bts()가 실행되지 않는다.
Thread로 실행하면 abc(), bts()가 동시에 실행된다.
함수 호출 버전 (~/test)
#include <stdio.h>
#include <unistd.h>
void abc(){
while(1) {
printf("ABC\n");
sleep(1);
}
}
void bts() {
while(1) {
printf("BTS\n");
sleep(1);
}
}
int main(){
abc();
bts();
return 0;
}
gcc sample.c -o ./gogo
./gogo
ABC
ABC
ABC
abc() 의 무한 반복이 끝나지 않아 bts() 는 한 번도 실행되지 않음sleep(s) : s초 동안 대기 (Linux 라이브러리, man page 3)~/test2)#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *abc(){
while(1) {
printf("ABC\n");
sleep(1);
}
return NULL;
}
void *bts(){
while(1) {
printf("BTS\n");
sleep(1);
}
return NULL;
}
int main()
{
pthread_t t1, t2;
pthread_create(&t1, NULL, abc, NULL);
pthread_create(&t2, NULL, bts, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
# 빌드 (소문자 L)
gcc sample.c -o ./gogo -lpthread
# 실행
./gogo

-> 결과: ABC, BTS가 번갈아 출력된다. 출력 순서는 실행할 때마다 다를 수 있다.

-> Thread를 먼저 생성했다고 먼저 실행되는 것이 아니다. 무엇이 먼저 동작할지는 스케줄러가 정한다.
void* 타입이므로 형변환해서 사용한다.#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void* abc(void* p){
int a = *(int*)p;
while(1){
printf("%d\n", a);
a++;
usleep(300*1000);
if( a>10 ) break;
}
return NULL;
}
int main(){
pthread_t tid;
int gv = 1;
pthread_create(&tid, NULL, abc, &gv);
pthread_join(tid, NULL);
printf("thread end\n");
return 0;
}

-> 결과: 1 ~ 10이 0.3초 간격으로 출력된 뒤 thread end가 출력된다.
#include <stdio.h>
#include <pthread.h>
struct Node{
int y;
int x;
};
void *abc(void *p){
struct Node *val = (struct Node *)p;
printf("%d %d\n", val->x, val->y);
return NULL;
}
int main(){
pthread_t tid;
struct Node val = {2, 4}; // y = 2, x = 4
pthread_create(&tid, NULL, abc, &val);
pthread_join(tid, NULL);
return 0;
}

-> 결과: 4 2
-> 자료의 실행 화면은 구조체 두 개(val1, val2)를 각각 Thread에 전달해 val1 4 2, val2 4 2 가 출력되는 형태 (소스는 일부만 수록)
-> void*는 만능이다. 변수, 구조체 상관없이 모두 받고, 역참조하는 방법도 같다.
#include <stdio.h>
#include <pthread.h>
void *run(void *arg){
int a = *(int*)arg;
printf("%d", a);
return NULL;
}
int main(){
pthread_t t[4];
for (int i = 0; i<4; i++) pthread_create(&t[i], NULL, run, &i);
for (int i = 0; i<4; i++) pthread_join(t[i], NULL);
return 0;
}

-> 결과: 2442, 3424처럼 실행할 때마다 다르고, 같은 값이 중복되거나 4가 출력된다.
-> Thread가 언제 동작할지는 스케줄러가 정한다. Thread는 동작할 때 i의 주소를 보고 값을 가져가는데, 그때 이미 i가 바뀌어 있을 수 있다.
#include <stdio.h>
#include <pthread.h>
void *run(void *arg){
int a = *(int*)arg;
printf("%d", a);
return NULL;
}
int main(){
pthread_t tid[4];
int id[4];
for (int i = 0; i<4; i++) {
id[i] = i;
pthread_create(&tid[i], NULL, run, &id[i]);
}
for (int i = 0; i<4; i++) pthread_join(tid[i], NULL);
return 0;
}

-> 결과: 0321, 0213처럼 0 ~ 3이 한 번씩 출력된다. 순서는 스케줄러가 정하므로 실행할 때마다 다르다.
.text, .bss, .data, .heap → 공유, .stack → Thread마다 독립abc() 함수만 수록 → main() 은 Thread를 두 번 생성하도록 작성#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int a = 100; // .data
int b; // .bss
int *p; // .heap 가리키는 포인터 변수
void* abc() {
int c = 10; // .stack
printf("=================\n");
printf(".data : %p\n", (void*)&a);
printf(".bss : %p\n", (void*)&b);
printf(".stack : %p\n", (void*)&c);
printf(".heap : %p\n", (void*)p );
return 0;
}
int main(){
p = (int*)malloc(4);
pthread_t t1, t2;
pthread_create(&t1, NULL, abc, NULL);
pthread_join(t1, NULL);
pthread_create(&t2, NULL, abc, NULL);
pthread_join(t2, NULL);
free(p);
return 0;
}
=================
.data : 0x62f991022010
.bss : 0x62f991022020
.stack : 0x770d97dfee44
.heap : 0x62f994e422a0
=================
.data : 0x62f991022010
.bss : 0x62f991022020
.stack : 0x770d975fde44
.heap : 0x62f994e422a0
.data, .bss, .heap 주소는 두 Thread에서 동일 → 공유.stack 주소는 Thread마다 다름 (위 출력은 자료의 실행 결과, 실행 환경마다 값은 다름)cnt 를 각각 10000번 ++ → 기대값은 40000#include <stdio.h>
#include <pthread.h>
int cnt=0; //.data 공유되는 메모리
void* run(void* arg){
for(int i=0; i<10000; i++) cnt++;
}
int main(){
pthread_t tid[4];
for(int i=0; i<4; i++) pthread_create(&tid[i], NULL, run, NULL);
for(int i=0; i<4; i++) pthread_join(tid[i], NULL);
printf("%d\n", cnt);
return 0;
}
gcc sample.c -o ./gogo -lpthread
./gogo
./gogo
./gogo
18244
18606
31539
cnt++ 는 읽기 → 증가 → 쓰기 세 단계 → 여러 Thread가 같은 값을 읽어 각자 증가시키면 증가분이 사라짐| API | 설명 |
|---|---|
pthread_mutex_t | mutex 핸들러 객체 |
pthread_mutex_init(핸들러, 속성) | mutex 초기화. 속성이 NULL 이면 default |
pthread_mutex_lock(핸들러) | mutex를 잠금. 이미 잠겨 있으면 풀릴 때까지 대기 |
pthread_mutex_unlock(핸들러) | 잠근 mutex를 풀기 |
pthread_mutex_destroy(핸들러) | mutex 제거. 잠긴 상태에서 제거하면 EBUSY 오류 |
#include <stdio.h>
#include <pthread.h>
pthread_mutex_t mlock;
int cnt=0;
void *run(){
pthread_mutex_lock(&mlock);
for(int i=0; i<10000; i++) cnt++;
pthread_mutex_unlock(&mlock);
}
int main(){
pthread_mutex_init(&mlock, NULL);
pthread_t tid[4];
for(int i=0; i<4; i++) pthread_create(&tid[i], NULL, run, NULL);
for(int i=0; i<4; i++) pthread_join(tid[i], NULL);
printf("%d\n", cnt);
pthread_mutex_destroy(&mlock);
return 0;
}
40000
40000
for 문을 lock / unlock 으로 감싸 한 번에 한 Thread만 실행40000 출력pthread_cancel(pthread_t) : 특정 Thread를 종료하기 위한 목적으로 사용, pthread_cancel() 을 받은 Thread는 pthread_exit() 실행, 반환값은 성공 여부killABC() 와 main() 앞부분만 수록 → abc() 와 pthread_join() 은 작성pthread_cancel() 로 종료할 Thread의 정보(t1)를 Thread 2 생성 시 arg 로 전달#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *abc(void *arg) {
while (1) {
printf("[T1] BTS\n");
sleep(1);
}
return NULL;
}
void *killABC(void *arg) {
int count = 0;
while (count < 10) {
count++;
printf("[T2] %d\n", count);
sleep(1);
}
// 스레드1을 종료
printf("Thread1 Kill\n");
pthread_cancel(*(pthread_t *)arg);
return NULL;
}
int main() {
setbuf(stdout, NULL);
pthread_t t1, t2;
pthread_create(&t1, NULL, abc, NULL);
pthread_create(&t2, NULL, killABC, (void *)&t1);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
[T1] BTS
[T2] 1
[T1] BTS
[T2] 2
...
[T2] 10
Thread1 Kill
[T2] 가 10까지 세고 나면 Thread 1을 종료 → [T1] BTS 출력이 멈추고 프로그램 종료setbuf(stdout, NULL) : 표준 출력 버퍼링을 꺼서 출력 순서를 바로 확인Thread1 Kill 뒤에 [T1] BTS 가 한 번 더 출력됨