#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>
// ์ ์ญ๋ณ์ g๋ฅผ 10์ผ๋ก ์ด๊ธฐํ
int g = 10;
// ์ค๋ ๋๋ก ์คํ๋ ํจ์
void *tfunction(void *data)
{
// main์์ ์ ๋ฌํ ์ธ์๋ฅผ int ํฌ์ธํฐ๋ก ํด์ํด ๊ฐ ์ฝ๊ธฐ
int id = *(int *)data;
// ์ ์ญ๋ณ์ g๋ฅผ ์ฆ๊ฐ์ํค๊ณ ํ์ฌ ์ค๋ ๋ id์ g ๊ฐ์ ์ถ๋ ฅ
// ++g๋ g๋ฅผ ๋จผ์ ์ฆ๊ฐ์ํจ ๋ค ์ถ๋ ฅ
printf("Hello! I'm thread #%d, g = %d\n", id, ++g);
// ์ค๋ ๋ ์ข
๋ฃ (pthread_exit์ผ๋ก NULL ๋ฐํ)
pthread_exit(NULL);
}
int main(void)
{
pthread_t t1; // ์ค๋ ๋ ID๋ฅผ ์ ์ฅํ ๋ณ์
int rcc; // pthread_create ๋ฐํ๊ฐ ์ ์ฅ
int t = 1; // ์ค๋ ๋์ ์ ๋ฌํ id ๊ฐ
printf("In main: creating thread.\n");
// ์ ์ค๋ ๋ ์์ฑ
// &t1 : ์์ฑ๋ ์ค๋ ๋ id ์ ์ฅ ์์น
// NULL : ๊ธฐ๋ณธ ์ค๋ ๋ ์์ฑ ์ฌ์ฉ
// tfunction : ์ค๋ ๋ ๋ฃจํด
// (void *)&t : t์ ์ฃผ์๋ฅผ void*๋ก ์ ๋ฌ (์ฃผ์: ์ง์ญ ๋ณ์ ์ฃผ์ ์ ๋ฌ)
rcc = pthread_create(&t1, NULL, tfunction, (void *)&t);
// ์์ฑ ์คํจ ์ฒ๋ฆฌ
if (rcc != 0) {
printf("Thread creation error.\n");
exit(1);
}
// ์์ฑํ ์ค๋ ๋๊ฐ ์ข
๋ฃ๋ ๋๊น์ง ๋๊ธฐ(์กฐ์ธ)
// ์ด ๋๋ฌธ์ main์ ์ง์ญ๋ณ์ t๊ฐ ์ค๋ ๋๊ฐ ์ฝ๊ธฐ ์ ์ ์๋ฉธ๋๋ ๋ฌธ์ ๋ ์๋ค.
pthread_join(t1, NULL);
return 0;
}
์ปดํ์ผ ๋ฐ ์คํ ๋ฐฉ๋ฒ
gcc -pthread -o thread_example thread_example.c
./thread_example
์์ ์ถ๋ ฅ
In main: creating thread.
Hello! I'm thread #1, g = 11
'6. CS ๊ธฐ์ด ๐ > Linux & Unix ๐ง' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [Linux/Unix] [10] Pthread (0) | 2025.12.08 |
|---|---|
| [Linux/Unix] [09] ํ๋ก์ธ์ค (0) | 2025.12.08 |
| [Linux/Unix] ๋จ์ถํค (0) | 2025.10.21 |
| [Linux/Unix] Cํ์ผ ์คํ (0) | 2025.10.21 |
| [Linux/Unix] shํ์ผ ์คํ (0) | 2025.10.21 |