multi_threads.c

Download
c 57 lines 1.2 KB
 1// multi_threads.c
 2// ์—ฌ๋Ÿฌ ์Šค๋ ˆ๋“œ ์ƒ์„ฑ ์˜ˆ์ œ
 3#include <stdio.h>
 4#include <stdlib.h>
 5#include <pthread.h>
 6
 7#define NUM_THREADS 5
 8
 9// ์Šค๋ ˆ๋“œ์— ์ „๋‹ฌํ•  ๋ฐ์ดํ„ฐ
10typedef struct {
11    int id;
12    char name[32];
13} ThreadData;
14
15void* thread_func(void* arg) {
16    ThreadData* data = (ThreadData*)arg;
17
18    printf("์Šค๋ ˆ๋“œ %d (%s) ์‹œ์ž‘\n", data->id, data->name);
19
20    // ์ž‘์—… ์‹œ๋ฎฌ๋ ˆ์ด์…˜
21    int sum = 0;
22    for (int i = 0; i < 1000000; i++) {
23        sum += i;
24    }
25
26    printf("์Šค๋ ˆ๋“œ %d ์™„๋ฃŒ: sum = %d\n", data->id, sum);
27
28    return NULL;
29}
30
31int main(void) {
32    pthread_t threads[NUM_THREADS];
33    ThreadData data[NUM_THREADS];
34
35    // ์Šค๋ ˆ๋“œ ์ƒ์„ฑ
36    for (int i = 0; i < NUM_THREADS; i++) {
37        data[i].id = i;
38        snprintf(data[i].name, sizeof(data[i].name), "Worker-%d", i);
39
40        int result = pthread_create(&threads[i], NULL, thread_func, &data[i]);
41        if (result != 0) {
42            fprintf(stderr, "์Šค๋ ˆ๋“œ %d ์ƒ์„ฑ ์‹คํŒจ\n", i);
43            exit(1);
44        }
45    }
46
47    printf("๋ชจ๋“  ์Šค๋ ˆ๋“œ ์ƒ์„ฑ ์™„๋ฃŒ. ๋Œ€๊ธฐ ์ค‘...\n");
48
49    // ๋ชจ๋“  ์Šค๋ ˆ๋“œ ๋Œ€๊ธฐ
50    for (int i = 0; i < NUM_THREADS; i++) {
51        pthread_join(threads[i], NULL);
52    }
53
54    printf("ํ”„๋กœ๊ทธ๋žจ ์ข…๋ฃŒ\n");
55    return 0;
56}