zhangmeng
2024-01-18 8fc23a3bb9f49e88478a2505fa7dee434ec50c16
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
57
58
59
60
61
62
63
64
65
66
67
68
#include "test.h"
using namespace std;
 
 
#define NTHREADS 4 
struct Targ targs[NTHREADS];
size_t qsize = 16;
bool stop = false;
void sigint_handler(int sig) {
  stop = true;
}
 
 
 
void* run (void *arg) {
  struct Targ * targ = (struct Targ * )arg;
  // SArrayLockFreeQueue<struct Item> *queue = QFactory::createArrayLockFreeQueue<struct Item> (targ->key, 10);
 // LockFreeQueue<struct Item> *queue = QueueFactory::createQueue<struct Item> (targ->key, qsize);
  SHMQueue<struct Item> *queue = new SHMQueue<struct Item>(targ->key, qsize);
  
  struct Item item;
  struct timespec timeout = {5, 0};
 
  int i = 0;
  while(!stop && (queue->pop_timeout(item, &timeout)) ) {
    printf("consumer(%d) 出队: {%d, %d}\n", targ->key, item.pic, item.info);
   // cout <<  item.pic << endl;
 
    i++;
    
  }
  delete queue;
  return (void *)i;
}
 
 
 
int main(int argc, char *argv[])
  signal(SIGINT,  sigint_handler);
  /* Create set containing two semaphores; initialize so that
     writer has first access to shared memory. */
    
  
  int i;
  pthread_t tids[NTHREADS];
  void *res[NTHREADS];
  struct Targ targs[NTHREADS];
   
 
  for (i = 0; i< NTHREADS; i++) {
    targs[i].key = i;
    pthread_create(&tids[i], NULL, run, (void *)&targs[i]);
  }
 
  for (i = 0; i< NTHREADS; i++) {
    if(pthread_join(tids[i], &res[i])!=0) {
      perror("productor pthread_join");
    } else {
      fprintf(stderr, "cosumer(%d) 读取了 %ld 条数据\n", i, (long)res[i]);
    }
  }
 
  
  mm_destroy();
  cerr << "cosumer quit" << endl;
  exit(EXIT_SUCCESS);
}