/docs/MyDocs

To get this branch, use:
bzr branch http://darksoft.org/webbzr/docs/MyDocs

« back to all changes in this revision

Viewing changes to Development/languages/C/Samples/pthreads/condition.c

  • Committer: Suren A. Chilingaryan
  • Date: 2009-04-09 03:21:08 UTC
  • Revision ID: csa@dside.dyndns.org-20090409032108-w4edamdh4adrgdu3
import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
#include <stdio.h>
 
2
#include <stdlib.h>
 
3
#include <unistd.h>
 
4
#include <pthread.h>
 
5
 
 
6
pthread_mutex_t mutex;
 
7
pthread_cond_t cond;
 
8
pthread_t thread1, thread2, thread3;
 
9
 
 
10
void *tfunc1(void *attr) {
 
11
    pthread_mutex_lock(&mutex);
 
12
    printf("locked1\n");
 
13
    sleep(2);
 
14
    printf("wait1 finished\n");
 
15
    pthread_cond_wait(&cond,&mutex);
 
16
    pthread_mutex_unlock(&mutex);
 
17
    printf("recive1\n");
 
18
    return NULL;
 
19
}
 
20
 
 
21
void *tfunc2(void *attr) {
 
22
    pthread_mutex_lock(&mutex);
 
23
    printf("locked2\n");
 
24
    sleep(3);
 
25
    printf("wait2 finished\n");
 
26
    pthread_cond_wait(&cond,&mutex);
 
27
    pthread_mutex_unlock(&mutex);
 
28
    printf("recive2\n");
 
29
    return NULL;
 
30
}
 
31
 
 
32
void *tfunc3(void *attr) {
 
33
    sleep(1);
 
34
    pthread_mutex_lock(&mutex);
 
35
    printf("locked for send\n");
 
36
    pthread_cond_broadcast(&cond);
 
37
    printf("send\n");
 
38
    pthread_mutex_unlock(&mutex);
 
39
    printf("unlocked from send\n");
 
40
    return NULL;
 
41
}
 
42
 
 
43
 
 
44
main() {
 
45
    void *ret;
 
46
    
 
47
    pthread_mutex_init(&mutex,NULL);
 
48
    pthread_cond_init(&cond,NULL);
 
49
 
 
50
    pthread_create(&thread1,NULL,tfunc1,NULL);
 
51
    pthread_create(&thread2,NULL,tfunc2,NULL);
 
52
    pthread_create(&thread3,NULL,tfunc3,NULL);
 
53
 
 
54
    pthread_join(thread1,&ret);
 
55
    pthread_join(thread2,&ret);
 
56
    pthread_join(thread3,&ret);
 
57
}