language: C (gcc-4.7.2)
date: 298 days 20 hours ago
link:
visibility: public
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
#include <stdio.h>
#include <stdlib.h>
#include "pthread.h"
#include "semaphore.h"
 
sem_t mutex;
int s = 0;
 
void* job (void* id) {
        printf("Start thread ID #%d\n", (int) id);
        while(1) {
                //sleep(1); //(1)
                sem_wait(&mutex);
                //sleep(1); //(2)
                        printf("Thread #%d is doing math. %d + 1 = %d.\n", (int) id, s, s+1);
                        s++;
                //sleep(1);     //(3)
                sem_post(&mutex);
                sleep(1);       //(4)
        }
}
 
int main() {
        pthread_t thread[10];
        
        int i;
        sem_init(&mutex, 0, 1);
        for (i = 0; i<10; ++i)
                pthread_create(&(thread[i]), NULL, job, (void*) i);
        
        sleep(100);
}
 
prog.c: In function ‘job’:
prog.c:19: warning: implicit declaration of function ‘sleep’
prog.c: In function ‘main’:
prog.c:32: warning: control reaches end of non-void function
/home/outB8N/ccWyCt1j.o: In function `main':
prog.c:(.text+0x2e): undefined reference to `sem_init'
prog.c:(.text+0x56): undefined reference to `pthread_create'
/home/outB8N/ccWyCt1j.o: In function `job':
prog.c:(.text+0xa8): undefined reference to `sem_wait'
prog.c:(.text+0xe4): undefined reference to `sem_post'
collect2: ld returned 1 exit status