-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.c
More file actions
103 lines (83 loc) · 2.4 KB
/
Copy pathserver.c
File metadata and controls
103 lines (83 loc) · 2.4 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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
#include "blg312e.h"
#include "request.h"
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <stdio.h>
pthread_mutex_t mutex;
sem_t empty, full;
int *buffer;
int buffer_size = 0;
int buffer_index_in = 0;
int buffer_index_out = 0;
void getargs(int *port, int *num_threads, int *buffer_size, int argc, char *argv[]) {
if (argc != 4) {
fprintf(stderr, "Usage: %s <port> <threads> <buffers>\n", argv[0]);
exit(1);
}
*port = atoi(argv[1]);
*num_threads = atoi(argv[2]);
*buffer_size = atoi(argv[3]);
}
void push_to_buffer(int connfd) {
sem_wait(&empty);
pthread_mutex_lock(&mutex);
buffer[buffer_index_in] = connfd;
buffer_index_in = (buffer_index_in + 1) % buffer_size;
pthread_mutex_unlock(&mutex);
sem_post(&full);
}
int pop_from_buffer() {
sem_wait(&full);
pthread_mutex_lock(&mutex);
int connfd = buffer[buffer_index_out];
buffer_index_out = (buffer_index_out + 1) % buffer_size;
pthread_mutex_unlock(&mutex);
sem_post(&empty);
return connfd;
}
void* client_handler(void* arg) {
while (1) {
int connfd = pop_from_buffer();
requestHandle(connfd);
//Close(connfd);
}
return NULL;
}
int main(int argc, char *argv[]) {
int port, num_threads;
pthread_t *thread_pool;
getargs(&port, &num_threads, &buffer_size, argc, argv);
pthread_mutex_init(&mutex, NULL);
sem_init(&empty, 0, buffer_size);
sem_init(&full, 0, 0);
buffer = (int *)malloc(sizeof(int) * buffer_size);
if (buffer == NULL) {
fprintf(stderr, "Error: malloc failed\n");
exit(1);
}
thread_pool = (pthread_t *)malloc(sizeof(pthread_t) * num_threads);
if (thread_pool == NULL) {
fprintf(stderr, "Error: malloc failed\n");
exit(1);
}
for (int i = 0; i < num_threads; i++) {
if (pthread_create(&thread_pool[i], NULL, client_handler, NULL) != 0) {
fprintf(stderr, "Error: pthread_create failed\n");
exit(1);
}
}
int listenfd = Open_listenfd(port);
while (1) {
struct sockaddr_in clientaddr;
socklen_t clientlen = sizeof(clientaddr);
int connfd = Accept(listenfd, (SA *)&clientaddr, &clientlen);
push_to_buffer(connfd);
}
Close(listenfd);
free(thread_pool);
pthread_mutex_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}