| 12
 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
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 
 | #include <stdio.h>
 #include <pthread.h>
 #include <stdlib.h>
 #include <unistd.h>
 #include <signal.h>
 #include <string.h>
 #include <semaphore.h>
 #include <vector>
 
 using namespace std;
 
 
 struct st_message
 {
 int  mesgid;
 char message[1024];
 }stmesg;
 
 vector<struct st_message> vcache;
 
 
 
 sem_t notify,lock;
 
 void  incache(int sig);
 void *outcache(void *arg);
 
 int main()
 {
 signal(15,incache);
 
 sem_init(¬ify,0,0);
 sem_init(&lock,0,1);
 
 
 pthread_t thid1,thid2,thid3;
 pthread_create(&thid1,NULL,outcache,NULL);
 pthread_create(&thid2,NULL,outcache,NULL);
 pthread_create(&thid3,NULL,outcache,NULL);
 
 pthread_join(thid1,NULL);
 pthread_join(thid2,NULL);
 pthread_join(thid3,NULL);
 
 sem_destroy(¬ify);
 sem_destroy(&lock);
 
 return 0;
 }
 
 void incache(int sig)
 {
 static int mesgid=1;
 
 struct st_message stmesg;
 memset(&stmesg,0,sizeof(struct st_message));
 
 
 sem_wait(&lock);
 
 
 stmesg.mesgid=mesgid++; vcache.push_back(stmesg);
 stmesg.mesgid=mesgid++; vcache.push_back(stmesg);
 
 
 
 
 sem_post(&lock);
 
 
 
 
 sem_post(¬ify);
 sem_post(¬ify);
 sem_post(¬ify);
 sem_post(¬ify);
 }
 
 void *outcache(void *arg)
 {
 struct st_message stmesg;
 
 while (true)
 {
 sem_wait(&lock);
 
 
 while (vcache.size()==0)
 {
 
 
 sem_post(&lock);
 sem_wait(¬ify);
 sem_wait(&lock);
 }
 
 
 memcpy(&stmesg,&vcache[0],sizeof(struct st_message));
 vcache.erase(vcache.begin());
 
 sem_post(&lock);
 
 
 printf("phid=%ld,mesgid=%d\n",pthread_self(),stmesg.mesgid);
 usleep(100);
 }
 }
 
 |