gpt4 book ai didi

c++ - CreateThread 参数值意外更改

转载 作者:太空狗 更新时间:2023-10-29 20:29:48 26 4
gpt4 key购买 nike

我正在尝试创建 4 个线程以在我的 4 个 CPU 内核上同时运行一个函数。我调用的函数将根据 val 变量值更改一些循环偏移量。

我试过了,但是它没有正确地增加 val 计数器,一些线程报告相同的值,它似乎是随机变化的:

int val = 1;
threads[0] = CreateThread(0, 0, my_thread_1, &val, 0, 0);
val++;
threads[1] = CreateThread(0, 0, my_thread_1, &val, 0, 0);
val++;
threads[2] = CreateThread(0, 0, my_thread_1, &val, 0, 0);
val++;
threads[3] = CreateThread(0, 0, my_thread_1, &val, 0, 0);

但这似乎工作得很好:

int val1 = 1;
int val2 = 2;
int val3 = 3;
int val4 = 4;
threads[0] = CreateThread(0, 0, my_thread_1, &val1, 0, 0);
threads[1] = CreateThread(0, 0, my_thread_1, &val2, 0, 0);
threads[2] = CreateThread(0, 0, my_thread_1, &val3, 0, 0);
threads[3] = CreateThread(0, 0, my_thread_1, &val4, 0, 0);

这可能是什么原因,如何正确地为线程提供一些参数?

这是我的功能:

DWORD WINAPI my_thread_1(void *params){ 
int val = *(int *)params;
...
}

最佳答案

失败的原因很简单,因为在您的第一个示例中,您将指针传递给所有 4 个线程的相同内存位置。您在传递指针 之前递增 的事实是无关紧要的,因为内存位置保持不变。

在您的第二个示例中,您改为将 4 个互斥指针传递给 4 个线程。因此,线程都是读取独立的值。

您可以稍微重组您的代码以帮助提高可维护性和灵 active :

int threadData[NTHREADS]; /* in the future this could be an array of structs */
HANDLE threads[NTHREADS];
int tt;

for (tt = 0; tt < NTHREADS; ++tt)
{
threadData[tt] = tt + 1; /* placeholder for actual logic */
threads[tt] = CreateThread(
NULL, /* lpThreadAttributes */
0, /* dwStackSize */
my_thread_1, /* lpStartAddress */
&threadData[tt], /* lpParameter: each thread will receive its own data */
0, /* dwCreationFlags */
NULL /* lpThreadId */);
}

/* Since threadData and threads are local to the enclosing scope,
* we must wait for them to finish here to ensure we don't read
* data we no longer own
*/
WaitForMultipleObjects(NTHREADS, threads, TRUE, INFINITE);

关于c++ - CreateThread 参数值意外更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976807/

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