1

Basically I've got two sockets that I'd like to run in parallel, so I don't have to wait for one socket to send data to receive data from the other etc. I can do this easily by forking, but, to be tidier, I'd like to know if there is a way to do it from the same process.

Something like:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void test(){
 sleep(5000);
}
int main(int argc, char *argv[])
{
 printf("%d\n",time(NULL));
 test();
 printf("%d\n",time(NULL));
 system("PAUSE");
 return 0; 
}

But both lines of output would be the same, as the sleep function is being processed 'somewhere else'.

I found an MSDN document about creating threads, but it talked about C-library functions not being safe for it, which worried me, I like my stdlib!

So, yeah, if you have any examples, you can just use sleep() as a placeholder, I'm pretty good with sockets :) I'm on Windows, but a Unix version would be nice as well, or better yet, one that works with both.

EDIT: Thanks for all your responses. I think I see what you mean: I have my two sockets, then I call select(), it returns all the sockets that are ready to receive/send data, I send/receive my data, then loop back. However, how could I implement this with accept(), as the socket hasn't yet been created?

4 Answers 4

3

The easiest approach is to make the sockets non-blocking, and use select() and/or WaitForMultipleObjects() to check for when you can read/write more data from/to each socket. That way the application can remain single-threaded while still appearing to service multiple sockets at the same time.

answered May 5, 2011 at 16:34
Sign up to request clarification or add additional context in comments.

1 Comment

Exactly! I would rather stay away from threads as much as possible. For I/O-bound tasks using asynchronous I/O seems to be much easier.
0

You can using omp sections or use pthread/WinThread

answered May 5, 2011 at 16:33

Comments

0

Or on Unix the normal solution would be fork()

answered May 5, 2011 at 16:34

2 Comments

Isn't fork too much coarse grain for this ?
@Joel - possibly select would be better - but for a large server fork() is normal
0

I don't know if it works (or has an analog) on Windows, but there's always select.

answered May 5, 2011 at 16:35

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.