pthread를 사용하는 멀티쓰레드 데몬이라면 pthread_mutex_lock()을 사용해 잠금을 할 것이며, 멀티프로세스 데몬이라면 세마포어를 사용 할 것이다.

흥미로운 부분은 많은 OS에서 뮤텍스를 이진 세마포어(binary semaphore)로 구현을 하고 있고, pthread 또한 멀티프로세스를 위한 잠금을 지원한다는 것이다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void) {
    pthread_mutex_t lock;
    pthread_mutexattr_t attr;

    if ( pthread_mutexattr_init(&attr) ) {
        puts("pthread_mutexattr_init() error");
        exit(1);
    }

    if ( pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED) ) {
        puts("pthread_mutexattr_setpshared() error");
        exit(1);
    }

    if ( pthread_mutex_init(&lock, &attr) ) {
        puts("pthread_mutex_init() error");
        exit(1);
    }

    int i;
    for ( i = 0; i < 5; i++ ) {
        if ( fork() == 0 ) {
            int j;
            for ( j = 0; j < 5; j ++ ) {
                if ( pthread_mutex_lock(&lock) ) {
                    puts("pthread_mutex_lock() error");
                    exit(1);
                }
                printf("pid = %d, lock\n", getpid());
                sleep(1);
                if ( pthread_mutex_unlock(&lock) ) {
                    puts("pthread_mutex_unlock() error");
                    exit(1);
                }
                printf("pid = %d, unlock\n", getpid());
            }
            break;
        }
        else {
            wait(NULL);
        }
    }

    pthread_mutexattr_destroy(&attr);
    pthread_mutex_destroy(&lock);

    return 0;
}

멀티프로세스에서 pthread_mutex_lock()으로 잠금을 하기 위해서는 17번째 줄처럼 pthread 뮤텍스를 설정 해주어야 한다. 이 설정은 fork()가 호출되기 전에 이뤄져야 한다는 점을 주의하자.