View Full Version : Need blocking for function

01-10-2009, 05:21 PM
I am using pthreads and sockets. What I am going to be having is multiple socket connections (no more than 5 or so). What I need is a recv() function on each of them in their own thread.

I just basically need to know what a good way is. The way I am doing it now runs my program at like 95% cpu usage. I can't believe this is good, but I don't know another way. Does anyone know how to keep recv blocking?

Below is some code, main is some pseudo code. As you can see, I just throw some while loops down.

int main (void)
create variables...

serv = connectserver(host, port);
if (serv)
create_recv_thread(serv, serv_recv, &listen_server);


int create_recv_thread(int server, buffer_t *buffer, void *function)
pthread_t recv_thread;
struct recv_args args;

args.server = server;
args.buffer = buffer;

return pthread_create(&recv_thread, NULL, function, &args);

void *listen_server(void *threadarg)
int result;
struct recv_args *my_data;
int server;
buffer_t *buffer;

my_data = (struct recv_args*)threadarg;

server = my_data->server;
buffer = my_data->buffer;

while (1)
result = recv(server, buffer->buffer_data, 2048, 0);
if (result > 0)
printf("%s %d bytes received through socket #%d\n", gettime(), result, server);
else if (result == 0)
printf("%s Connection to socket #%d closed\n", gettime(), server);
printf("%s recv error\n", gettime());

01-10-2009, 05:36 PM
Your problem is the "while(1);" in your main thread.

01-10-2009, 05:43 PM
But I don't want the program to end. I need to keep it open because with some data I receive it will trigger my program to send data. I want to keep the connection alive until I choose to kill it.

01-10-2009, 05:50 PM
But I don't want the program to end.

Then use appropriate functions: pthread_join() for instance instead of while(1). Besides, recv() is blocking by default except if you switched your socket streams to non-blocking which doesn't seem to be the case.