基本上我有两个想要并行运行的套接字,因此我不必等待一个套接字发送数据来接收来自另一个套接字的数据等。
我可以通过分叉轻松地做到这一点,但是,为了更整洁,我想知道是否有一种方法可以从同一过程中做到这一点。
类似于:
#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;
}
但是两行输出将是相同的,因为睡眠函数正在“其他地方”处理。
我找到了一个关于创建线程的 MSDN 文档,但它谈到 C 库函数对它来说不安全,这让我很担心,我喜欢我的 stdlib!
所以,是的,如果你有任何例子,你可以使用 sleep() 作为占位符,我对套接字非常擅长:)我在 Windows 上,但 Unix 版本也很好,或者更好,一种同时适用于两者的产品。
编辑:感谢您的所有回复。
我想我明白你的意思:我有两个套接字,然后我调用 select(),它返回所有准备好接收/发送数据的套接字,我发送/接收我的数据,然后循环回来。
但是,由于套接字尚未创建,我该如何使用accept() 来实现这一点呢?
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)
最简单的方法是使套接字成为非阻塞,并使用
select()
和/或WaitForMultipleObjects()
来检查何时可以从/读取/写入更多数据到每个插座。这样,应用程序可以保持单线程,同时仍然可以同时为多个套接字提供服务。The easiest approach is to make the sockets non-blocking, and use
select()
and/orWaitForMultipleObjects()
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.您可以使用 omp 部分或使用 pthread/WinThread
You can using omp sections or use pthread/WinThread
或者在 Unix 上,正常的解决方案是 fork()
Or on Unix the normal solution would be fork()
我不知道它在 Windows 上是否有效(或有模拟),但总是有 选择。
I don't know if it works (or has an analog) on Windows, but there's always select.