简体   繁体   English

C语言:并行线程?

[英]C language: Parallel threads?

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! 我找到了一个有关创建线程的MSDN文档,但其中谈到了C库函数对此并不安全,这让我担心,我喜欢我的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. 所以,是的,如果您有任何示例,则可以只使用sleep()作为占位符,我对套接字非常满意:)我在Windows上,但是Unix版本也很好,或者更好,一个可以同时使用两者。

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. 我想我明白你的意思了:我有两个套接字,然后调用select(),它返回所有准备好接收/发送数据的套接字,我发送/接收数据,然后环回。 However, how could I implement this with accept(), as the socket hasn't yet been created? 但是,由于尚未创建套接字,我该如何用accept()实现呢?

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. 最简单的方法是使套接字无阻塞,并使用select()和/或WaitForMultipleObjects()检查何时可以从每个套接字读取更多数据或向每个套接字写入更多数据。 That way the application can remain single-threaded while still appearing to service multiple sockets at the same time. 这样,应用程序可以保持单线程状态,同时仍然可以同时为多个套接字提供服务。

您可以使用omp节或使用pthread / WinThread

或者在Unix上,正常的解决方案是fork()

我不知道它是否可以在Windows上运行(或具有模拟功能),但始终会选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM