๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
6. CS ๊ธฐ์ดˆ ๐Ÿ“š/Linux & Unix ๐Ÿง

[Linux/Unix][8-2]

by lxvxxu 2025. 11. 11.

 

 

#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