c++ 使用_beginthread向线程传递值并避免C风格的强制转换?

dced5bon  于 2023-07-01  发布在  其他
关注(0)|答案(1)|浏览(79)

我的程序创建了一个线程,但我在使用Visual Studio进行代码分析时得到了“不要使用C风格的强制转换”。

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

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

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

我尝试了static_cast<LPVOID>&bValue2,但它给出了一个错误。
_beginthread中转换的正确格式是什么?

7uzetpgm

7uzetpgm1#

下面是一个例子:

// 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 <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;
}

相关问题