// thread1.c#include<stdio.h>#include<stdlib.h>#include<pthread.h>void*print_message_function(void*ptr) {char*message; message = (char*) ptr;printf("[Thread started] %s \n", message);}main() {pthread_t thread;constchar*message ="Hello World...";int iret; iret =pthread_create(&thread,NULL, print_message_function, (void*) message); /* Wait till thread is complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and thread before the thread has completed. */pthread_join(thread,NULL);printf("Thread returns: %d\n", iret);exit(0);}
// thread2.c// forks off four threads that print their ids#include<pthread.h>#include<stdio.h>void*printme(void*ip) {int*i; i = (int*) ip;printf("Hi. I'm thread %d\n",*i);returnNULL;}main() {int i, vals[4];pthread_t tids[4];void*retval;for (i =0; i <4; i++) { vals[i] = i;pthread_create(tids + i,NULL, printme, vals + i); }for (i =0; i <4; i++) {printf("Trying to join with tid %d\n", i);pthread_join(tids[i],&retval);printf("Joined with tid %d\n", i); }}
ทำการคอมไพล์ และทดสอบรันโปรแกรม
$ gcc -o thread2 thread2.c -lpthread
$ ./thread2
Trying to join with tid 0
Hi. I'm thread 1
Hi. I'm thread 2
Hi. I'm thread 3
Hi. I'm thread 0
Joined with tid 0
Trying to join with tid 1
Joined with tid 1
Trying to join with tid 2
Joined with tid 2
Trying to join with tid 3
Joined with tid 3
// thread3.c#include<stdio.h>#include<stdlib.h>#include<pthread.h>void*print_message_function(void*ptr);main() {pthread_t thread1, thread2;constchar*message1 ="Thread 1’s Message";constchar*message2 ="Thread 2’s Message";int iret1, iret2; /* Create independent threads each of which will execute function */ iret1 =pthread_create(&thread1,NULL, print_message_function, (void*) message1); iret2 =pthread_create(&thread2,NULL, print_message_function, (void*) message2); /* Wait till threads are complete before main continues. Unless we */ /* wait we run the risk of executing an exit which will terminate */ /* the process and all threads before the threads have completed. */pthread_join(thread1,NULL);pthread_join(thread2,NULL);printf("Thread 1 returns: %d\n", iret1);printf("Thread 2 returns: %d\n", iret2);exit(0);}void*print_message_function(void*ptr) {char*message; message = (char*) ptr;printf("%s \n", message);}
// thread4.c#include<pthread.h>#include<stdio.h>void*printme(void*v) {int*i; i = (int*) v;printf("Hi. I'm thread %d\n",*i);pthread_exit(NULL);}main() {int i, vals[4];pthread_t tids[4];void*retval;for (i =0; i <4; i++) { vals[i] = i;pthread_create(tids + i,NULL, printme, (void*) (vals + i)); }for (i =0; i <4; i++) {printf("Trying to join with tid %d\n", i);pthread_join(tids[i],&retval);printf("Joined with tid %d\n", i); }pthread_exit(NULL);}
ทำการคอมไพล์ และทดสอบรันโปรแกรม
$ gcc -o thread4 thread4.c -lpthread
$ ./thread4
Trying to join with tid 0
Hi. I'm thread 3
Hi. I'm thread 2
Hi. I'm thread 1
Hi. I'm thread 0
Joined with tid 0
Trying to join with tid 1
Joined with tid 1
Trying to join with tid 2
Joined with tid 2
Trying to join with tid 3
Joined with tid 3
// thread5.c#include<pthread.h>#include<stdio.h>void*printme(i)int*i; {printf("Hi. I'm thread %d\n",*i);exit(NULL);}main() {int i, vals[4];pthread_t tids[4];void*retval;for (i =0; i <4; i++) { vals[i] = i;pthread_create(tids + i,NULL, printme, vals + i); }for (i =0; i <4; i++) {printf("Trying to join with tid %d\n", i);pthread_join(tids[i],&retval);printf("Joined with tid %d\n", i); }}
ทำการคอมไพล์ และทดสอบรันโปรแกรม
$ gcc -o thread5 thread5.c -lpthread
$ ./thread5
Trying to join with tid 0
Hi. I'm thread 3
$ gcc -o thread6 thread6.c -lpthread
$ ./thread6
How are you?
How are you?
How are you?
How are you?
How are you?
How are you?
Hello!!
Hello!!
Hello!!
Hello!!
Hello!!
How are you?
How are you?
Hello!!
How are you?
...
$ gcc -o thread7 thread7.c -lpthread
$ ./thread7
Enter a string: Hello
Enter a string: The string entered is : ==== Hello
Fine?
Enter a string: The string entered is : ==== Fine?
Yes
Enter a string: The string entered is : ==== Yes
/* server.c C socket server example, handles multiple clients using threads */#include<stdio.h>#include<string.h>//strlen#include<stdlib.h>//strlen#include<sys/socket.h>#include<arpa/inet.h>//inet_addr#include<unistd.h>//write#include<pthread.h>//for threading , link with lpthread//the thread functionvoid*connection_handler(void*);intmain(int argc,char*argv[]) {int socket_desc, client_sock, c;struct sockaddr_in server, client;//Create socket socket_desc =socket(AF_INET, SOCK_STREAM,0);if (socket_desc ==-1) {printf("Could not create socket"); }puts("Socket created");//Prepare the sockaddr_in structureserver.sin_family = AF_INET;server.sin_addr.s_addr = INADDR_ANY;server.sin_port =htons(8888);//Bindif (bind(socket_desc, (struct sockaddr*) &server,sizeof(server))<0) {//print the error messageperror("bind failed. Error");return1; }puts("bind done");//Listenlisten(socket_desc,3);//Accept and incoming connectionputs("Waiting for incoming connections..."); c =sizeof(struct sockaddr_in);//Accept and incoming connectionputs("Waiting for incoming connections..."); c =sizeof(struct sockaddr_in);pthread_t thread_id;while ((client_sock =accept(socket_desc, (struct sockaddr*) &client, (socklen_t*) &c))) {puts("Connection accepted");if (pthread_create(&thread_id,NULL, connection_handler, (void*) &client_sock)<0) {perror("could not create thread");return1; }//Now join the thread , so that we dont terminate before the thread//pthread_join( thread_id , NULL);puts("Handler assigned"); }if (client_sock <0) {perror("accept failed");return1; }return0;}/* * This will handle connection for each client * */void*connection_handler(void*socket_desc) {//Get the socket descriptorint sock =*(int*) socket_desc;int read_size;char*message, client_message[2000];//Send some messages to the client message ="Greetings! I am your connection handler\n";write(sock, message, strlen(message)); message ="Now type something and i shall repeat what you type \n";write(sock, message, strlen(message));//Receive a message from clientwhile ((read_size =recv(sock, client_message,2000,0)) >0) {//end of string marker client_message[read_size] ='\0';//Send the message back to clientwrite(sock, client_message, strlen(client_message));//clear the message buffermemset(client_message,0,2000); }if (read_size ==0) {puts("Client disconnected");fflush(stdout); } elseif (read_size ==-1) {perror("recv failed"); }return0;}
สำหรับโปรแกรมลูกข่ายดังแสดงข้างล่างนี้
/* client.c Client was fixed port 8888 for connection to server. */#include<stdio.h>#include<string.h>#include<strings.h>#include<stdlib.h>#include<netdb.h>#include<netinet/in.h>#include<sys/types.h>#include<sys/socket.h>intprint_usage() {printf("\n");printf("Usage : client HOST_ADDRESS\n");printf("Connect to host by using port 8888 for communication\n");printf("\n");return0;}intmain(int argc,char*argv[]) {struct sockaddr_in serv_addr, cli_addr;struct hostent *server;int serv_fd, cli_fd;char msg_buffer[256];if (argc !=2) {print_usage();return-1; }system("clear");printf("********** CLIENT **********\n");// 1. create socketif ((serv_fd =socket(AF_INET, SOCK_STREAM,0)) <0) {printf("Error : creating socket !!!\n"); } else {printf("1. Creating socket -> OK\n"); }// 2. connect to host server =gethostbyname(argv[1]);bzero((char*) &serv_addr,sizeof(serv_addr));serv_addr.sin_family = AF_INET;serv_addr.sin_port =htons(8888);bcopy((char*) server->h_addr, (char*) &serv_addr.sin_addr.s_addr,server->h_length);if (connect(serv_fd, (struct sockaddr*) &serv_addr,sizeof(serv_addr))<0) {printf("Error : connecting to server !!!\n");return-1; } else {printf("2. Connecting to server -> OK\n"); }// 3. communication printf("********* TALKING **********\n");// 3.1 receive ready message from serverbzero(msg_buffer,256);recv(serv_fd, msg_buffer,256,0);printf("[server] : %s\n", msg_buffer);// 3.2 answer to serverbzero(msg_buffer,256);printf("[client] : ");scanf("%s", msg_buffer);send(serv_fd, msg_buffer, strlen(msg_buffer),0);// 3.3 ok communicationbzero(msg_buffer,256);recv(serv_fd, msg_buffer,256,0);printf("[server] : %s\n", msg_buffer);return0;}
คอมไพล์และรันโปรแกรมทั้งสองดังนี้
$ gcc -o server server.c -lpthread
$ ./server
Socket created
bind done
Waiting for incoming connections...
Waiting for incoming connections...
$ gcc -o client client.c
$ ./client 127.0.0.1
********** CLIENT **********
1. Creating socket -> OK
2. Connecting to server -> OK
********* TALKING **********
[server] : Greetings! I am your connection handler
Now type something and i shall repeat what you type
[client] : Hi
[server] : Hi
Assoc. Prof. Wiroon Sriborrirux, Founder of Advance Innovation Center (AIC) and Bangsaen Design House (BDH), Electrical Engineering Department, Faculty of Engineering, Burapha University