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 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
| #include <stdlib.h> #include <stdio.h> #include <string.h> #include <netdb.h> #include <sys/socket.h> #include <arpa/inet.h> #include <ctype.h> #include <unistd.h> #include <pthread.h> #include "queue.h"
#define BUFSIZE 2048 #define BACKLOG 500 #define NUMTHREADS 10 #define PORTNO 8888
struct queue *work_queue;
pthread_mutex_t queue_mutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t queue_cond=PTHREAD_COND_INITIALIZER;
void *handle_conn(void *arg){ int recvlen; int conn_sock; char buf[BUFSIZE]; long long limit; long long sum=0,i;
while(1){
pthread_mutex_lock(&queue_mutex); while(isempty(work_queue)){ pthread_cond_wait(&queue_cond,&queue_mutex); } conn_sock=work_queue->head->item; dequeue(work_queue); pthread_mutex_unlock(&queue_mutex);
recvlen = read(conn_sock, &limit, sizeof(limit));
if (recvlen > 0) { printf("Received number by thread %d: %lld\n", (int)pthread_self(), limit); } else{ printf("uh oh - something went wrong!\n"); }
sum=0; for(i=1;i<=limit;i++){ sum+=i; } write(conn_sock,&sum,sizeof(sum)); } return NULL; }
int main(int argc, char **argv) { struct sockaddr_in myaddr; struct sockaddr_in remaddr; int conn_sock; socklen_t addrlen = sizeof(remaddr); int recvlen; int servSocket; int msgcnt = 0; char buf[BUFSIZE]; int *sock_ptr; int i; pthread_t tid[NUMTHREADS]; unsigned short port_num=PORTNO;
work_queue=create_queue();
for(i=0;i<NUMTHREADS;i++){ pthread_create(&tid[i],NULL,handle_conn,NULL); }
if ((servSocket = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("Error: cannot create socket\n"); exit(1); }
memset((char *)&myaddr, 0, sizeof(myaddr)); myaddr.sin_family = AF_INET; myaddr.sin_addr.s_addr = htonl(INADDR_ANY); myaddr.sin_port = htons(port_num);
if (bind(servSocket, (struct sockaddr *)&myaddr, sizeof(myaddr)) < 0) { printf("Error: bind failed\n"); exit(1); }
listen(servSocket,BACKLOG); printf("waiting on port %d\n",port_num);
while (1){
conn_sock=accept(servSocket,(struct sockaddr *)&remaddr, &addrlen);
pthread_mutex_lock(&queue_mutex); enqueue(work_queue,conn_sock); pthread_cond_broadcast(&queue_cond); pthread_mutex_unlock(&queue_mutex); } destroy_queue(work_queue); printf("Server program ended normally\n"); return 0; }
|