Skip to content

Commit 98a6786

Browse files
committed
add basic concurrency
1 parent 2cfcae7 commit 98a6786

File tree

1 file changed

+24
-7
lines changed

1 file changed

+24
-7
lines changed

proxylab-handout/proxy.c

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -77,10 +77,10 @@ void forward_response(int infd, int outfd)
7777
fprintf(stderr, "Content-length: %d\n", content_length);
7878
#endif
7979
// read content
80-
char *content_buf = (char *)malloc((content_length+1)*sizeof(char));
80+
char *content_buf = (char *)Malloc((content_length+1)*sizeof(char));
8181
Rio_readnb(&rio, content_buf, content_length);
8282
string_appendn(&response, content_buf, (size_t)content_length);
83-
free(content_buf);
83+
Free(content_buf);
8484
}
8585
if (Rio_readlineb(&rio, buf, MAXLINE) != 0) {
8686
// TODO: error handling
@@ -125,8 +125,6 @@ void forward(int fromfd)
125125
#endif
126126

127127
sprintf(request_buf, "%s %s %s\r\n", method, dir, version);
128-
int clientfd = Open_clientfd(
129-
host, port);
130128

131129
int has_host = 0;
132130
// request headers
@@ -166,12 +164,25 @@ void forward(int fromfd)
166164
#ifdef DEBUG
167165
fprintf(stderr, "request buf:\n%s\n", request_buf);
168166
#endif
167+
int clientfd = Open_clientfd(
168+
host, port);
169169
Rio_writen(clientfd, request_buf, strlen(request_buf));
170170

171171
// receive data
172172
// read_response(clientfd);
173173

174174
forward_response(clientfd, fromfd);
175+
Close(clientfd);
176+
}
177+
178+
void *thread(void *vargp)
179+
{
180+
int connfd = *((int*)vargp);
181+
Pthread_detach(pthread_self());
182+
Free(vargp);
183+
forward(connfd);
184+
Close(connfd);
185+
return NULL;
175186
}
176187

177188

@@ -186,14 +197,20 @@ int main(int argc, char **argv)
186197
int listenfd = Open_listenfd(argv[1]);
187198
struct sockaddr_storage clientaddr;
188199
socklen_t clientlen = sizeof(clientaddr);
200+
int *connfdp;
189201
while (1) {
190-
int connfd = Accept(listenfd,
202+
connfdp = Malloc(sizeof(int));
203+
*connfdp = Accept(listenfd,
191204
(SA *)&clientaddr,
192205
&clientlen);
193-
if (connfd == -1) {
206+
if (*connfdp == -1) {
207+
Free(connfdp);
194208
// TODO: error report
209+
} else {
210+
// TODO: use thread pool
211+
pthread_t tid;
212+
Pthread_create(&tid, NULL, thread, connfdp);
195213
}
196-
forward(connfd);
197214
}
198215
return 0;
199216
}

0 commit comments

Comments
 (0)