传递值给一个线程,使用 _beginthread,并避免使用 C 风格的强制类型转换?

huangapple go评论80阅读模式
英文:

Passing values to a thread with _beginthread and avoiding C-style casts?

问题

#include <windows.h>
#include <process.h>
#include <iostream>

void myThread(void* threadParams)
{
    int* x = static_cast<int*>(threadParams);
    std::cout << "*x: " << *x;
}

int main()
{
    BOOL bValue2 = TRUE;
    _beginthread(myThread, 0, static_cast<void*>(&bValue2));
    Sleep(10000);
}
英文:

My program creates a thread but I'm getting a "Don't use C-style casts" in my code analysis with Visual Studio.

#include &lt;windows.h&gt;
#include &lt;process.h&gt;
#include &lt;iostream&gt;

void myThread(void * threadParams)
{
int* x = (int*)threadParams;
std::cout &lt;&lt; &quot;*x: &quot; &lt;&lt; *x;
}

int main()
{
BOOL bValue2 = TRUE;
_beginthread(myThread, 0, (LPVOID)&amp;bValue2);
Sleep(10000);
}

I tried static_cast&lt;LPVOID&gt;&amp;bValue2 but it gives an error.

What is the proper format for casting in _beginthread?

答案1

得分: 3

以下是您要翻译的代码部分:

#include <thread>
#include <string>
#include <iostream>

void my_thread_function(const std::string& hello, int x)
{
    std::cout << hello << "\n";
    std::cout << x << "\n";
}

int main()
{
    int x{ 42 };
    std::string hello{ "hello world" };

    std::thread thread{ [=] { my_thread_function(hello, x); } }; // [=] capture x and hello by value
    thread.join(); // wait for thread to complete (no need to sleep);

    return 0;
}

如果您需要进一步的帮助,请随时提问。

英文:

Here is an example :

// no need to inlcude OS specific headers
// thread support is in since C++11
// https://en.cppreference.com/w/cpp/thread/thread
// https://en.cppreference.com/w/cpp/language/lambda

#include &lt;thread&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;

void my_thread_function(const std::string&amp; hello, int x)
{
	std::cout &lt;&lt; hello &lt;&lt; &quot;\n&quot;;
	std::cout &lt;&lt; x &lt;&lt; &quot;\n&quot;;
}

int main()
{
	int x{ 42 };
	std::string hello{ &quot;hello world&quot; };

	std::thread thread{ [=] { my_thread_function(hello, x); } }; // [=] capture x and hello by value 
	thread.join(); // wait for thread to complete (no need to sleep);

	return 0;
}

huangapple
  • 本文由 发表于 2023年6月29日 19:01:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76580419.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定