#include #include #include #include #include #include #include #include #include #include #include #include #include #define SOCKET_SERVER const int NUM_THREADS = 100000; //const int THREAD_STACK_SIZE = 1024 * 78; const int THREAD_STACK_SIZE = 1024 * 4; //const int THREAD_STACK_SIZE = 1024 * 64; const int PORT = 7501; const int SOCKET_ACCEPT_BACKLOG = 8192; const int ECHO_BUFSIZE = 8192; const int NUM_PROCS = 1; // 64: 32292 // 78: 32292 // 79: 32290 // 80: 32290 void *waste_time(void *args) { char buf[1024]; int i = 0; while(1) { buf[i] = i; i = (i + 1) % 1024; pause(); } } void *echo_socket(void *args) { int fd = (int) args; char buf[ECHO_BUFSIZE]; int readBytes, justWroteBytes, alreadyWroteBytes; while ((readBytes = read(fd, buf, ECHO_BUFSIZE)) > 0) { alreadyWroteBytes = 0; do { if ((justWroteBytes = write(fd,buf + alreadyWroteBytes,readBytes-alreadyWroteBytes)) <= 0) { if (justWroteBytes < 0) perror("write failed in thread"); return NULL; } alreadyWroteBytes += justWroteBytes; } while (readBytes > alreadyWroteBytes); } /* If we get here, readBytes is either 0 for EOF, or -1 for error. */ if (readBytes < 0) { perror("read failed in thread"); } return NULL; } int main() { pthread_attr_t thread_attr; pthread_t thr[NUM_THREADS]; int i; #ifdef SOCKET_SERVER int sock; struct sockaddr_in serverAddr; const int on = 1; #endif #ifdef SOCKET_SERVER if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("Error creating socket"); exit(1); } if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on)) < 0) { perror("Error setting socket option SO_REUSEADDR"); exit(1); } memset((void *)&serverAddr, 0, sizeof(serverAddr)); serverAddr.sin_family = AF_INET; serverAddr.sin_addr.s_addr = INADDR_ANY; serverAddr.sin_port = htons(PORT); if (bind(sock,(const struct sockaddr*)&serverAddr, sizeof(serverAddr)) < 0) { perror("Error binding socket"); exit(1); } if (listen(sock, SOCKET_ACCEPT_BACKLOG) < 0) return -1; #endif if (pthread_attr_init(&thread_attr) != 0) { perror("Error initializing thread attributes"); exit(1); } if (pthread_attr_setstacksize(&thread_attr, PTHREAD_STACK_MIN + THREAD_STACK_SIZE) != 0) { perror("Error initializing thread attributes"); exit(1); } pid_t pid; int forkRet; for(i=0;i