JURVANOERLE.nl

This is a threadpool server that I have made in C for a school assignment. It creates a number of threads (number of cores on server * 2 + 1) and every time someone connects, a new thread is spawned to handle it. It does work but unfortunately not on this server. Here is the source code though

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <signal.h>

//the port number on which clients can connect.
#define PORT 			"3490"
//the amount of clients that are able to connect to this server.
#define BACK_LOG		10
//the default amount of bytes that the server will sent to the client.
#define DEFAULT_BUFLEN 		1024
//the max number of threads that this server can handle.
#define NUM_THREADS 		sysconf( _SC_NPROCESSORS_ONLN ) * 2 + 1

//create a global mutex lock that can be used by every thread.
pthread_mutex_t	lock = PTHREAD_MUTEX_INITIALIZER;

//store incoming connecting clients.
typedef struct incm_cnnt_clnt
{
	struct sockaddr_storage *their_addr;
	socklen_t	sock_size;
	int incm_sock;	
} incoming_client;

struct threadpool_task_t
{
	//the thread that is performing the task (-1 when no thread is handling the task).
	int owner;
	
	int id;
	//the time that the task was added to the queue.
	int time_added;
	//the amount of time that the task can wait before it has to be performed.
	int deadline;
	
	//this is a pointer to the connecting function that will be performed once the server has accept( )ed the clients connect( ).
	void ( *task )( void* );
	void *params;
};

typedef struct threadpool_task_t threadpool_task_t;

void handle_connection( void* params );

struct threadpool_t
{
	//this is the queue of tasks. The queue will be handled FIFO and when a task is completed,
	//it's thread will be removed from the queue and placed back into the pool.	
	threadpool_task_t	*queue;
	//this is the size of the queue.
	int 			queue_size;
	//this is the amount of tasks that can be placed inside of the queue.
	int				queue_buffer;
	
	//a flag indicating that the threadpool was initialized
	int 			is_initialized;
};

//define the struct (I forgot this the first time (or rather did not knwo about it) [thank you Google/Wikipedia!] )
typedef struct threadpool_t threadpool_t;

//define a global scope threadpool 'instance'
threadpool_t *threadpool;
void threadpool_queue_task( threadpool_task_t *task )
{
	pthread_mutex_lock( &lock );
	if ( threadpool -> is_initialized == 0 )
	{
		printf( "threadpool not initialized yet." );
	}
	else if ( threadpool -> queue_size < threadpool -> queue_buffer )
	{
		//queue the task unto the threadpool.
		threadpool -> queue[threadpool -> queue_size++]	= *task;
	} else printf( "cannot add more tasks to the queue." );
	pthread_mutex_unlock( &lock );
}

threadpool_task_t *get_task( int i )
{
	threadpool_task_t *task	= &threadpool -> queue[i];
	threadpool_task_t *temp;
	temp 					= ( threadpool_task_t* )malloc( sizeof( threadpool_task_t ) );
	
	temp -> task			= *task -> task;
	temp -> params			= task -> params;
	temp ->	owner			= task -> owner;
	
	for ( i; i <  threadpool -> queue_size - 1; ++i )
	{
		threadpool -> queue[i] = threadpool -> queue[i + 1];
	}
	--threadpool -> queue_size;
	
	return temp;
}

void *threadpool_init_wrkr_thrd( void *params )
{
	while ( 1 )
	{
		//lock, so there aren't two jobs distributed at once.
		pthread_mutex_lock( &lock );
		
		threadpool_task_t *task	= NULL;
		//if there is a task on the queue
		if ( threadpool -> queue_size > 0 )
		{
			task 			= get_task( 0 );
			task -> owner	= pthread_self( );
		}
		pthread_mutex_unlock( &lock );
		if ( task != NULL )
		{
			( *task -> task )( task -> params );
		}
	}
}


void threadpool_init( params )
{	
	//do nothing if the threadpool has already been initialized.
	if ( threadpool -> is_initialized == 1 ) return;
	//lock the mutex.
	pthread_mutex_lock( &lock );
	
	threadpool -> queue_size	= 0;
	threadpool -> queue			= ( threadpool_task_t* )malloc( sizeof( threadpool_task_t ) * NUM_THREADS );
	threadpool -> queue_buffer	= NUM_THREADS;
	
	int i;
	for ( i = 0; i < NUM_THREADS; ++i )
	{
		pthread_t	t;
		pthread_create( &t, NULL, threadpool_init_wrkr_thrd, ( void* )i );
	}
	
	//the threadpool is now initialized.
	threadpool -> is_initialized	= 1;
	printf( "initialized the queue\n" );
	pthread_mutex_unlock( &lock );
}

int bind_to_sock( struct addrinfo *res )
{
	struct addrinfo *p;
	int yes = 1, sock_addr; 
	// loop through all the tcp_results and bind to the first we can
	for( p = res; p != NULL; p = p -> ai_next ) 
	{
		if ( ( sock_addr = socket( p -> ai_family, p -> ai_socktype, p -> ai_protocol ) ) == -1 ) 
		{
			perror( "server: socket" );
			continue;
		}

		if ( setsockopt( sock_addr, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof( int ) ) == -1 ) 
		{
			perror( "setsockopt" );
			exit( 1 );
		}

		if ( bind( sock_addr, p -> ai_addr, p -> ai_addrlen ) == -1 ) 
		{
			close( sock_addr );
			perror( "server: bind" );
			continue;
		}
		break;
	}
	return sock_addr;
}

// get sockaddr, IPv4 or IPv6:
void *get_in_addr( struct sockaddr *sa )
{
	if ( sa -> sa_family == AF_INET ) 
	{
		return &( ( ( struct sockaddr_in* )sa ) -> sin_addr );
	}
	return &( ( ( struct sockaddr_in6* )sa ) -> sin6_addr );
}

int are_equal( char *s1, int len1, char *s2, int len2 )
{
	if ( len1 != len2 )
	{	
        return 0; // They must be different
	}
	int i = 0;
    for ( i; i < len1; ++i )
    {
		if ( s1[i] != s2[i] )
			return 0;  // They are different
    }
    return 1;  // They must be the same.
}

void handle_tcp_connection( void *params )
{
	incoming_client *client 			= ( incoming_client* )params;
	struct sockaddr_storage *their_addr = &client -> their_addr;
	int incm_sock 						= client -> incm_sock;
	
	char s[INET6_ADDRSTRLEN];
	inet_ntop( their_addr -> ss_family,	get_in_addr( ( struct sockaddr * )their_addr ),	s, sizeof s );
	printf( "server: got connection from %s\n", s );
	char cmsg[DEFAULT_BUFLEN];
	
	if ( send( incm_sock, "connected with server.", 49, 0 ) == -1 )
	{
		perror( "send" );
	}
	
	while ( 1 )
	{
		int len = 0;
		len = recv( incm_sock, cmsg, DEFAULT_BUFLEN - 1, 0 );
		
		if ( len == 0 )
		{
			printf( "connection closed by client: %s.\n", s );
			shutdown( incm_sock, 2 );
			break;
		}
		cmsg[len]	= '\0';
		
		if ( are_equal( cmsg, len, "close", 5 ) )
		{
			printf( "connection closed by client: %s.\n", s );
			shutdown( incm_sock, 2 );			
			break;
		} else printf( "%s\n", cmsg );
	}	
}

int task_id	= 0;
int threadpool_add_task( void( *function )( void* ), void* params, int deadline )
{
	threadpool_task_t *task;
	task = ( threadpool_task_t* )malloc( sizeof( threadpool_task_t ) );
	
	task -> task 		= function;
	task -> params		= params;
	task -> owner		= -1;
	task -> time_added	= time( 0 );
	task -> deadline	= deadline;
	task -> id			= task_id++;
	
	threadpool_queue_task( task );
	return task -> id;
}

void *handle_deadline_thread( void *params )
{
	printf( "handle task. It's deadline has passed.\n" );
	//lock, so there aren't two jobs distributed at once.
	pthread_mutex_lock( &lock );
	
	threadpool_task_t *task	= get_task( ( int )params );
	task -> owner	= pthread_self( );
	
	pthread_mutex_unlock( &lock );
	if ( task != NULL )
	{
		( *task -> task )( task -> params );
	}	
	pthread_exit( 0 );
}

void *threadpool_check_deadlines( void *params )
{
	while( 1 )
	{
		pthread_mutex_lock( &lock );
		
		//loop through the queue.
		int i = 0;
		for ( i; i < threadpool -> queue_size; ++i )
		{
			if ( ( time( 0 ) - threadpool -> queue[i].time_added ) > threadpool -> queue[i].deadline )
			{
				//if the deadline is passed, spawn a new thread.
				pthread_t t;
				pthread_create( &t, 0, handle_deadline_thread, ( void* )i );
			}
		}		
		pthread_mutex_unlock( &lock );
		usleep( 50000 );
	}
}

struct addrinfo tcp_addrinfo, *tcp_res;
int status;
void *main_tcp_func( void *params )
{
	printf( "waiting for TCP clients...\n" );
	//in this function, the server will create a socket, bind to it and listen on that socket with the given port number.
	memset( &tcp_addrinfo, 0, sizeof( tcp_addrinfo ) );
	tcp_addrinfo.ai_family		= AF_UNSPEC;
	tcp_addrinfo.ai_socktype	= SOCK_STREAM;
	tcp_addrinfo.ai_flags		= AI_PASSIVE;
	
	if ( ( status = getaddrinfo( NULL, PORT, &tcp_addrinfo, &tcp_res ) ) != 0 )
	{
		fprintf( stderr, "canīt find that host: %s", gai_strerror( status ) );
		return;
	}
	//create a new socket.
	int sock_addr = bind_to_sock( tcp_res );
	
	//listen to incoming connection calls.
	listen( sock_addr, BACK_LOG );
	
	int i = 0;
	//the server is now listening for incoming connections. However, we still need to accept those connections in a thread.
	while ( 1 )
	{
		incoming_client *client = ( incoming_client* )malloc( sizeof( incoming_client ) );
		client -> sock_size	= sizeof client -> their_addr;
		client -> incm_sock	= accept( sock_addr, ( struct sockaddr * )&client -> their_addr, &client -> sock_size );
				
		if ( threadpool -> queue_size >= NUM_THREADS )
		{			
			send( client -> incm_sock, "busy", 4, 0 );
			shutdown( client -> incm_sock, 2 );
		}
		
		if ( client -> incm_sock == -1 )
		{
			printf( "connecting to server failed." );
			continue;
		}
		
		//the connection has been made. Now we can start a new thread to handle incoming messages.
		threadpool_add_task( handle_tcp_connection, ( void* )client, 10 );
	}
	pthread_exit( NULL );
}

void handle_udp_connection( void *params )
{
	printf( "waiting for UDP packets...\n" );
	int num_bytes;
	struct sockaddr_storage their_addr;
	socklen_t addr_len 	= sizeof their_addr;
	char buf[DEFAULT_BUFLEN];
	
	while ( 1 )
	{
		if ( ( num_bytes = recvfrom( ( int )params, buf, DEFAULT_BUFLEN -1 , 0, ( struct sockaddr * ) &their_addr, &addr_len ) ) == -1 ) 
		{
			perror( "recvfrom" );
			exit( 1 );
		}
		buf[num_bytes]	= '\n';
		printf( "%s\n", buf );
	}
}

struct addrinfo udp_addrinfo, *udp_res;
int udp_sock_adrr;
void *main_udp_func( void* params )
{
	memset( &udp_addrinfo, 0, sizeof( udp_addrinfo ) );
	udp_addrinfo.ai_family		= AF_UNSPEC;
	udp_addrinfo.ai_socktype	= SOCK_DGRAM;
	udp_addrinfo.ai_flags		= AI_PASSIVE;
	
	if ( status = getaddrinfo( NULL, PORT, &udp_addrinfo, &udp_res ) == -1 )
	{
		perror( "get addressinfo.\n" );
		exit( 2 );
	}
	
 	int sock = bind_to_sock( udp_res );

	//now we can start to receive packets.
	threadpool_add_task( handle_udp_connection, ( void* )sock, 2 );
}

pthread_t tcp_thread, udp_thread;
pthread_t deadline_thread;
int main ( int arg, char *argv[] )
{
	threadpool		= ( threadpool_t* )malloc( sizeof( threadpool_t ) );
	tcp_thread		= ( pthread_t* )malloc( sizeof( pthread_t ) );
	udp_thread		= ( pthread_t* )malloc( sizeof( pthread_t ) );
	deadline_thread		= ( pthread_t* )malloc( sizeof( pthread_t ) );

	threadpool_init( );
	
	//let's create a task manager that will distribute threads.
	pthread_create( tcp_thread, 0, main_tcp_func, NULL );
	pthread_create( udp_thread, 0, main_udp_func, NULL );
	pthread_create( deadline_thread, 0, threadpool_check_deadlines, NULL );
	pthread_exit( NULL );
	return 0;
}