Repository navigation
Expand file tree
/
Copy pathos.cpp
More file actions
85 lines (83 loc) · 2.27 KB
/
Copy pathos.cpp
File metadata and controls
85 lines (83 loc) · 2.27 KB
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <malloc.h>
#include <unistd.h>
class Node
{
public:
int num;
Node* next;
};
Node* head;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
class Mm
{
public:
static Node* avail;
static Node* alloc;
Mm(){
pthread_t pro;
pthread_t con;
head=NULL;
int err;
err = pthread_create(&pro, NULL, mallocos,NULL);
printf("The produce thread is running...\n");
err = pthread_create(&con, NULL, freeos,NULL);
printf("The consume thread is running...\n");
pthread_join(pro, NULL);
pthread_join(con, NULL);
};
static void *mallocos(void *ptr){
while(1)
{
avail=(Node*)malloc(sizeof(Node));
srand(time(0));
avail->num=rand()%100+1;
printf("produce %d\n",avail->num);
pthread_mutex_lock(&mutex);
avail->next=head;
head=avail;
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
sleep(1);
}
};
static void *freeos(void *ptr){
while(1)
{
pthread_mutex_lock(&mutex);
if (NULL == head)
pthread_cond_wait(&cond, &mutex);
avail = head;
if (avail->next)
{
while (avail->next)
{
alloc = avail;
avail = avail->next;
}
printf("Consume %d\n", avail->num);
free(avail);
alloc->next = avail = NULL;
}
else
{
printf("Consume %d\n", avail->num);
free(avail);
head = avail = NULL; /// < 必须的,且注意head!
}
pthread_mutex_unlock(&mutex);
sleep(2);
}
};
private:
char* memory;
};
Node* Mm::alloc;
Node* Mm::avail;
int main(){
Mm model;
return 0;
}