๐ ์ด๋ฒ ์ฃผ ํด์ฆ๋ ๋ฉํฐํ๋ก์ธ์ค/๋ฉํฐ์ค๋ ๋ ์ ํ ๊ธฐ์ค, ๋ฐ๋๋ฝ ํด๊ฒฐ, ์ธ๋งํฌ์ด์ ๋ฎคํ ์ค์ ์ฐจ์ด, C ์ฝ๋ ๋ถ์ ๋ฐ ๋ฉ๋ชจ๋ฆฌ ๋์์ ๋ํ ๊ธฐ๋ณธ ๊ฐ๋ ์ ์ ๊ฒํ๋ ๋ฌธ์ ์์ต๋๋ค.
โ ๋ชจ๋ฒ ๋ต์:
โ ๋ชจ๋ฒ ๋ต์:
๊ต์ฐฉ ์ํ ์๋ฐฉ(Prevention)
โ ๋ฐ๋๋ฝ ๋ฐ์ ์กฐ๊ฑด ์ค ํ๋ ์ด์์ ์ฌ์ ์ ์ ๊ฑฐ (์: ์ํ ๋๊ธฐ ๋ฐฉ์ง)
ํํผ(Avoidance)
โ ์์ ์์ฒญ ์ ํ์ฌ ์ํ์์ ๋ฐ๋๋ฝ์ด ๋ฐ์ํ ๊ฐ๋ฅ์ฑ์ด ์๋์ง ์ฌ์ ์ ๊ณ์ฐ (์: Bankerโs Algorithm)
ํ์ง ๋ฐ ํ๋ณต(Detection & Recovery)
โ ๋ฐ๋๋ฝ ๋ฐ์์ ํ์ฉํ๋, ์ฃผ๊ธฐ์ ์ผ๋ก ํ์งํ๊ณ ๋ฌธ์ ๊ฐ ์๊ธฐ๋ฉด ํ๋ก์ธ์ค ์ข
๋ฃ ๋ฑ์ผ๋ก ํ๋ณต
โ ๋ชจ๋ฒ ๋ต์:
ํญ๋ชฉ | Semaphore | Mutex |
---|---|---|
๊ฐ๋ | ์ ์๊ฐ์ผ๋ก ๊ด๋ฆฌ๋๋ ๋๊ธฐํ ๋๊ตฌ | ์ํธ๋ฐฐ์ ๋ฅผ ์ํ ๋ฝ ๋๊ตฌ |
์์ ๊ฐ์ | 0๊ฐ ์ด์ ์์ ์ ์ด ๊ฐ๋ฅ | ๋จ์ผ ์์ ์ ์ด์ ์ฌ์ฉ๋จ |
์์ ๊ถ | ์์ ๊ฐ๋ ์์ | ํน์ ์ค๋ ๋๊ฐ ๋ฝ์ ์์ |
์ฌ์ฉ ํจ์ | sema_down() , sema_up() | lock_acquire() , lock_release() |
#include <stdio.h>
int f(int x, int *py, int **ppz) {
int y, z;
**ppz += 1;
z = **ppz;
*py += 2;
y = *py;
x += 3;
return x + y + z;
}
int main() {
int c, *b, **a;
c = 4;
b = &c;
a = &b;
printf("%d\n", f(c, b, a));
return 0;
}
โ ๋ชจ๋ฒ ๋ต์:
c = 4
**ppz += 1
โ c = 5
*py += 2
โ c = 7
x += 3
โ x = 7
โ x + y + z = 7 + 7 + 5 = 19
๐ข ์ ๋ต: 19
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int data;
char *description;
} item;
item* create_item(int data, const char *desc) {
item *new_item = (item *)malloc(sizeof(item));
if (new_item == NULL) {
return NULL;
}
new_item->data = data;
new_item->description = (char *)malloc(strlen(desc) + 1);
strcpy(new_item->description, desc);
return new_item;
}
int main() {
item *myItem = create_item(5, "Test Item");
printf("Item: %d, Description: %s\n", myItem->data, myItem->description);
// ๋ค๋ฅธ ์์
์ํ
free(myItem); // ๋ฉ๋ชจ๋ฆฌ ํด์
return 0;
}
โ ๋ชจ๋ฒ ๋ต์:
๋ฌธ์ ์ : description
ํ๋์ ํ ๋นํ malloc
๋ฉ๋ชจ๋ฆฌ๋ฅผ ํด์ ํ์ง ์์
โ ๋ฉ๋ชจ๋ฆฌ ๋์ ๋ฐ์
ํด๊ฒฐ ๋ฐฉ์:
free(myItem->description); // description ํด์
free(myItem); // ๊ตฌ์กฐ์ฒด ํด์
free(myItem->description);
free(myItem);
๐จ Tip: ๊ตฌ์กฐ์ฒด ์์ ํฌ์ธํฐ๊ฐ ์์ ๊ฒฝ์ฐ, ๊ตฌ์กฐ์ฒด ์์ฒด๋ฅผ freeํ๊ธฐ ์ ์ ๋ด๋ถ ๋์ ํ ๋น ์์ญ๋ freeํด์ค์ผ ์์ ํฉ๋๋ค.
์ด ์ ๋๋ฉด ์ ๊ธ ์ด์์ง์