Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void serve_connection (void* sockfd) {
- ssize_t n, result;
- char line[MAXLINE];
- connection_t conn;
- connection_init (&conn);
- conn.sockfd = (int)sockfd;
- while (! shutting_down) {
- if ((n = readline (&conn, line, MAXLINE)) == 0) goto quit;
- /* connection closed by other end */
- if (shutting_down) goto quit;
- if (n < 0) {
- perror ("readline failed");
- goto quit;
- }
- result = writen (&conn, line, n);
- if (shutting_down) goto quit;
- if (result != n) {
- perror ("writen failed");
- goto quit;
- }
- }
- quit:
- pthread_mutex_lock(&lock);
- --running;
- pthread_mutex_unlock(&lock);
- close (conn.sockfd);
- pthread_cond_signal(&con);
- }
- /* shared data between threads */
- int running;
- pthread_mutex_t lock;
- pthread_cond_t con;
- int
- main (int argc, char **argv) {
- /* numConn is the number of connections
- running is the number of currently running threads */
- running = 0;
- int connfd, listenfd, numConn;
- socklen_t clilen;
- struct sockaddr_in cliaddr;
- if(argc < 2) numConn = 4;
- else {numConn = atoi(argv[1]);}
- pthread_t threads[numConn];
- /* make all threads detached */
- pthread_attr_t attr;
- pthread_attr_init(&attr);
- pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
- /* initialize lock and con to protect 'running' variable */
- pthread_mutex_init(&lock, NULL);
- pthread_cond_init(&con, NULL);
- install_siginthandler();
- open_listening_socket (&listenfd);
- listen (listenfd, numConn);
- /* allow a default of 4 queued connection requests (unless otherwise specified) before refusing */
- while (! shutting_down) {
- errno = 0;
- clilen = sizeof (cliaddr); /* length of address can vary, by protocol */
- /* wait for running threads to close if numConn has been exceeded */
- pthread_mutex_lock(&lock);
- while(running == numConn)
- {
- pthread_cond_wait(&con, &lock);
- }
- pthread_mutex_unlock(&lock);
- if ((connfd = accept (listenfd, (struct sockaddr *) &cliaddr, &clilen)) < 0) {
- if (errno != EINTR) ERR_QUIT ("accept");
- /* otherwise try again, unless we are shutting down */
- } else {
- pthread_create(&threads[running], &attr, (void*)&serve_connection, (void*)connfd);
- pthread_mutex_lock(&lock);
- ++running;
- pthread_mutex_unlock(&lock);
- /* server_handoff (connfd); process the connection */
- }
- }
- /* waiting for any open threads */
- pthread_mutex_lock(&lock);
- while(running > 0)
- {
- printf("Waiting on thread #%dn", running);
- pthread_cond_wait(&con, &lock);
- }
- pthread_mutex_unlock(&lock);
- pthread_cond_destroy(&con);
- pthread_mutex_destroy(&lock);
- close (listenfd);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement