int main(int argc, char **argv) { int listenfd, *connfd, port, clientlen, i; struct sockaddr_in clientaddr; pthread_t tid; port_queue prod_var; /* Check command line args */ if (argc != 2) { fprintf(stderr, "usage: %s <port>\n", argv[0]); exit(1); } port = atoi(argv[1]); connfdqp = queueInit (); prod_var.port = port; prod_var.q = connfdqp; Pthread_create(&tid, NULL, producer, &prod_var); printf("Producer thread created %u\n", (unsigned int) tid); Pthread_detach(tid); printf ("Producer thread detached\n"); for (i = 0; i < MAXTHREAD; i++) { Pthread_create(&tid, NULL, consumer, connfdqp); printf("Consumer thread created %u\n", (unsigned int) tid); Pthread_detach(tid); printf("Consumer thread detached\n"); } printf("Main thread exited\n"); Pthread_exit(NULL); }
int main() { int i; pthread_t tid; char *msgs[] = {"hello from foo", "hello from bar"}; ptr = msgs; for (i = 0; i < N; ++i) Pthread_create(&tid, NULL, thread, (void *)i); Pthread_exit(NULL); }
/* * job - a thread function to process http request and response * * basically it finish three tasks: * forward request to server when no cache hit * forward response to client from server or cache * safely close file descriptor and exit thread when error * */ void job(void *arg) { Pthread_detach(pthread_self()); // get file descriptor and free the pointer int to_client_fd = *(int *)arg; Free(arg); int to_server_fd = -1; int rc = 0; char cache_id[MAXLINE]; char cache_content[MAX_OBJECT_SIZE]; unsigned int cache_length; rc = forward_to_server(to_client_fd, &to_server_fd, cache_id, cache_content, &cache_length); if (rc == -1) { // some error close_fd(&to_client_fd, &to_server_fd); Pthread_exit(NULL); } else if (rc == 1) { // found in cache, read from cache if (forward_to_client_from_cache(to_client_fd, cache_content, cache_length) == -1) { close_fd(&to_client_fd, &to_server_fd); Pthread_exit(NULL); } } else if (rc == 2) { // non GET method, POST etc. if (forward_to_client(to_client_fd, to_server_fd) == -1) { close_fd(&to_client_fd, &to_server_fd); Pthread_exit(NULL); } } else { // GET method and write to cache if (forward_to_client_and_cache(to_client_fd, to_server_fd, cache_id, cache_content) == -1) { close_fd(&to_client_fd, &to_server_fd); Pthread_exit(NULL); } } close_fd(&to_client_fd, &to_server_fd); return; }
/* these errors only terminate thread, not the whole application */ void unix_error(char *msg) /* unix-style error */ { fprintf(stderr, "%s: %s\n", msg, strerror(errno)); fflush(stderr); Pthread_exit(0); }
void app_error(char *msg) /* application error */ { fprintf(stderr, "%s\n", msg); fflush(stderr); Pthread_exit(0); }
void dns_error(char *msg) /* dns-style error */ { fprintf(stderr, "%s: DNS error %d\n", msg, h_errno); fflush(stderr); Pthread_exit(0); }
void posix_error(int code, char *msg) /* posix-style error */ { fprintf(stderr, "%s: %s\n", msg, strerror(code)); fflush(stderr); Pthread_exit(0); }