2020/2/18 custom protocol multi-threaded model

Multi-process model has some drawbacks: start a child process for each client, this will cause take up a lot of system resources, server processing power of concurrent requests will be getting worse. For the server to handle large concurrent case, more often it is using multi-threading model.


Multi-threading model

<Pthread.h> header;

Sub-thread should be promptly released:

Linux threads under separate state and have combined state, the thread isolated state can recover their own resources, combined with state pthread_join must use these functions to recover. So we start to separate state, when after the child thread thread resources will be released independently.

When a thread is created, if the second argument is NULL, the thread property is the default parameters, default attributes need to run pthread_join before the end of the program, to merge all the threads together, if you want to create your own thread return data back to the main thread, We need to use the default thread attributes. And if you do not return the data to the child thread the main thread, the main thread does not need to block waiting for a child thread, you can set separate property, created out of threads.

 

With pthread_create to create threads function: pthread_create (& th, & attr , th_fn, (void *) fd)

& Th: a pointer to the thread identifier;

& Attr: pthread_t * The second parameter used to set the thread attributes;

th_fn: starting address of the thread running function (function name);

(Void *) fd: Parameter (void *) (*) (void *) running the function (of type void *)

pthread_attr_setdetachstate function, if you need to run sub-thread end terminates immediately release system resources, you can set detachstate thread attributes pthread_attr_t structure in the following manner, so that the thread start to separate state.

pthread_attr_setdetachstate (pthread_attr_t * attr, int detachstate), the first parameter is the name of a separated state of the sub-thread, the second parameter is optionally PTHREAD_CREATE_DETACHED separate thread, PTHREAD _CREATE_JOINABLE non detached thread.

pthread_attr_t attr create a sub-thread structure;

pthread_attr_init (& attr) initialization sub-thread;

pthread_attr_setdetachstate (& attr, PTHREAD_CREATE_DETACHED) separating thread is provided

With pthread_attr_destroy after the function, delete initialize allocated memory space, and start calling sub-process function, we need to use it to destroy the resource occupied by the child process.

 

Main thread is responsible to call accept to get connected to the client; to separate the state of two-way communication with the client thread promoter


Source

void out_fd(int fd)
{
	struct sockaddr_in addr;
	socklen_t len = sizeof(addr);
//从fd中获得连接的客户端相关信息,用getpeername函数,并放置到sockaddr结构体中
	if(getpeername(fd, (struct sockaddr*)&addr, &len) < 0){
		perror("getpeername error");
		return;
	}
	char ip[16];
	memset(ip, 0, sizeof(ip));
	int port = ntohs(addr.sin_port);
	inet_ntop(AF_INET, &addr.sin_addr.s_addr, ip, sizeof(ip));
	printf("%16s(%5d) closed!\n", ip, port);
	
}

//定义线程运行函数
void* th_fn(void *arg)
{
	int fd = (int)arg;
	do_service(fd);
	out_fd(fd);
	close(fd);//step 6

	return (void*)0;
}

int main(int argc, char *argv[])
{
...
	//设置线程的分离属性
	pthread_attr_t attr;
	pthread_attr_init(&attr);
	pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

	while(1){
	//主控线程负责去调用accept获得客户端的连接
		int fd = accept(sockfd,	NULL, NULL);
		if(fd < 0) {
 			perror("accept error");
			continue;
		}

		/*step 5 IO function: read/write 启动子线程去调用IO函数*/
		 
	//启动子线程:以默认方式or以分离状态(子线程是服务于客户的双向通信)
		pthread_t th;
		int err;
		//以分离状态启动子线程
		if((err = pthread_create(&th, &attr, th_fn, (void*)(long)fd)) != 0)
		{
			perror("pthread create error");
		}
		pthread_attr_destroy(&attr);

	}
	return 0;
}

note

#include <pthread.h> thread header
#include <arpa / inet.h> network byte order conversion header


Compile and run

gcc -o bin/echo_tcp_server_th -Iinclude obj/msg.o src/echo_tcp_server_th.c -lpthread

Remember to include the header files compiled

Multi-threading model will be relatively small overhead on the server, after dealing with concurrency, multi-threaded multi-process than the much better!

 

Released seven original articles · won praise 4 · Views 546

Guess you like

Origin blog.csdn.net/Xinyue_Lu/article/details/104364086