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

84 views Asked by At

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

#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);
}

I tried static_cast<LPVOID>&bValue2 but it gives an error.

What is the proper format for casting in _beginthread?

1

There are 1 answers

4
Pepijn Kramer On

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