-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver_thread_pool_.cpp
More file actions
94 lines (88 loc) · 1.66 KB
/
server_thread_pool_.cpp
File metadata and controls
94 lines (88 loc) · 1.66 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
#include <sys/types.h>
#include <sys/socket.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <assert.h>
#include <arpa/inet.h>
#include <list>
using namespace std;
#define THREAD_N 20
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
list<int> queue;
void *entry(void *)
{
while (1)
{
pthread_mutex_lock(&mutex);
while (!queue.size())
{
assert(!pthread_cond_wait(&cond, &mutex));
}
int sock = queue.front();
queue.pop_front();
pthread_mutex_unlock(&mutex);
if (!sock)
{
break;
}
char buf[256] = {0};
read(sock, buf, sizeof(buf));
printf("%s\n", buf);
close(sock);
}
}
int main()
{
int listener;
struct sockaddr_in addr;
char buf[256];
int bytes_read;
int sock;
listener = socket(AF_INET, SOCK_STREAM, 0);
if (listener < 0)
{
perror("sock\n");
exit(1);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(5000);
addr.sin_addr.s_addr = inet_addr("0.0.0.0");
if (bind(listener, (struct sockaddr *)&addr, sizeof(addr)) < 0)
{
perror("bind\n");
exit(1);
}
if(listen(listener, 1) == -1)
{
perror("listener\n");
exit(1);
}
pthread_t *pool = new pthread_t[THREAD_N];
for (int i = 0; i < THREAD_N; i++)
{
pthread_create(pool + i, NULL, entry, NULL);
}
while (1)
{
sock = accept(listener, NULL, NULL);
if (sock < 0)
{
perror("accept\n");
exit(1);
}
pthread_mutex_lock(&mutex);
queue.push_back(sock);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
close(sock);
}
for (int i = 0; i < THREAD_N; i++)
{
pthread_join(pool[i], NULL);
}
delete [] pool;
return 0;
}