CreateThread参数值意外更改

Roo*_*kie 3 c++ winapi multithreading visual-c++

我试图创建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);
Run Code Online (Sandbox Code Playgroud)

但这似乎工作得很好:

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);
Run Code Online (Sandbox Code Playgroud)

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

这是我的功能:

DWORD WINAPI my_thread_1(void *params){ 
    int val = *(int *)params;
...
}
Run Code Online (Sandbox Code Playgroud)

use*_*116 5

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

在第二个示例中,您将传递4个相互排斥的指向 4个线程的指针.因此,线程都读取独立的值.

您可以稍微重新构建代码以帮助实现可维护性和灵活性:

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);
Run Code Online (Sandbox Code Playgroud)