gpt4 book ai didi

c++ - 在 C++ 控制台应用程序中运行两个线程

转载 作者:太空宇宙 更新时间:2023-11-04 13:39:01 25 4
gpt4 key购买 nike

我在创建使用 while 循环的 C++ 应用程序时遇到问题。

int checkIP(const char *IP)
{
WSAData version; //We need to check the version.
WORD mkword=MAKEWORD(2,2);
int what=WSAStartup(mkword,&version);
if(what!=0){
std::cout<<"This version is not supported! - \n"<<WSAGetLastError()<<std::endl;
}
else{
std::cout<<"Good - Everything fine!\n"<<std::endl;
}

SOCKET u_sock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(u_sock==INVALID_SOCKET)
std::cout<<"Creating socket fail\n";

else
std::cout<<"It was okay to create the socket\n";

//Socket address information
sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_addr.s_addr=inet_addr("192.168.0.90");
addr.sin_port=htons(80);
/*==========Addressing finished==========*/

//Now we connect
int conn=connect(u_sock,(SOCKADDR*)&addr,sizeof(addr));
return conn;
}

这是我检查 ip 的函数。我想并行运行这个函数。喜欢

void start(const char* ip)
{
while(checkIP == SOCKET_ERROR)
{
try to connect the ip...
}
}

在我的主程序中,我想运行这个启动函数,但我不想等待这个启动函数的响应......我需要这个函数应该被调用并并行地完成它的工作,并且程序像 farword 一样。 ..

int Ipcheck = checkIP("192.168.10.90");
if(Ipcheck == SOCKET_ERROR)
{
ofstream _Log;
_Log.open ("Log.txt",std::ios_base::app);
_Log << "Unable to connect to "<<IP<<endl;
_Log.close();
start();
BSTR bstrr = SysAllocString(L"Error");
return bstrr;
}

就像在这段代码中,系统调用启动函数,但我希望它只是调用函数并反手做所有事情,编译器继续执行下一条语句 BSTR 立即返回值...请帮助我做到这一点...抱歉我的英语不好...请提供示例代码如何以反手或并行方式运行 while 循环事件...

最佳答案

要创建线程,请查看 std::thread

同时查看总是非常有用的文档 http://www.codeproject.com/Articles/540912/Cplusplus-Threads-Make-your-multitasking-life-e

通读本文,帮助您了解如何安全地创建线程、停止/避免数据竞争和锁定线程。线程是很棒的东西,可以加快处理速度,在 UI 后面运行更新等,而其他东西正在运行。

如果您还需要,请在这里给我发消息 :) jack

关于c++ - 在 C++ 控制台应用程序中运行两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28494892/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com