As I could not find a way out using thread specific data for socket descriptor as depicted in this question A question on shared library and thread specific data , I am planning to declare a process wide global array with each row having two elements pthread_t and int(for socketfd). So whenever a thread needs to communicate with the server it will look up the array for its socket fd using its identity(pthread_self())and use it to communicate.
But I was wondering instead of dynamically allocating and deallocating space for this structure whenever there is a connection setup or disconnected respectively , if I have a array with the size of say 1000 …is it too big/inefficient(I will have to search too)? 1000 threads will not exist at the same time. so the array will not always be full.
Thanks
The space required to store an array like this with only 1000 elements will not likely be a problem unless you’re running on very resource limited hardware. As for the performance, it really depends on how frequently you search the array… if the searches won’t occur frequently during the life of each thread, the speed will probably be adequate unless you have very high standards for performance.
However, if you’re planning on creating a thread for each connection and terminating the thread when done, then a better approach would be to design a structure containing all the information the thread needs from the main program (like the socket file descriptor) and pass a pointer to it as the thread’s argument when you create the thread.
If you do use a thread per connection, you might also want to look into setting a smaller-than-default stack size for the threads as well, so that creating a large number of threads doesn’t eat too much memory for stack space.