【发布时间】:2020-12-09 13:04:55
【问题描述】:
我正在调试一个使用std::thread 运行函数的多线程应用程序。调试时我到达以下代码。
extern "C" uintptr_t __cdecl _beginthreadex(
void* const security_descriptor,
unsigned int const stack_size,
_beginthreadex_proc_type const procedure,
void* const context,
unsigned int const creation_flags,
unsigned int* const thread_id_result
)
{
_VALIDATE_RETURN(procedure != nullptr, EINVAL, 0);
unique_thread_parameter parameter(create_thread_parameter(procedure, context));
if (!parameter)
{
return 0;
}
DWORD thread_id;
HANDLE const thread_handle = CreateThread(
reinterpret_cast<LPSECURITY_ATTRIBUTES>(security_descriptor),
stack_size,
thread_start<_beginthreadex_proc_type, true>,
parameter.get(),
creation_flags,
&thread_id);
if (!thread_handle)
{
__acrt_errno_map_os_error(GetLastError());
return 0;
}
if (thread_id_result)
{
*thread_id_result = thread_id;
}
// If we successfully created the thread, the thread now owns its parameter:
parameter.detach();
return reinterpret_cast<uintptr_t>(thread_handle);
}
但我不明白函数的地址如何传递给CreateThread API。为什么使用thread_start<_beginthreadex_proc_type, true>,以及函数的地址将如何通过该语句计算以供线程运行?
【问题讨论】:
-
函数地址和参数存放在
parameter。 -
“使用
std::thread”。虽然我看到线程代码,但我没有看到std::thread。您想对该代码进行现代化改造以使用std::thread吗? -
@Jarod42 看起来 OP 正在研究 std::thread 的实现
-
你从哪里得到这个 src 代码?通过此代码线程开始从公共入口点
thread_start<_beginthreadex_proc_type, true>执行。此函数从parameter获取用户定义的入口点并调用它 -
@RbMm 这是 MSVC 库代码。
标签: c++ multithreading winapi