C++ - 传递给线程的数据是否应该是易失性的? [英] C++ - Should data passed to a thread be volatile?

查看:28
本文介绍了C++ - 传递给线程的数据是否应该是易失性的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Microsoft Visual C++ 中,我可以调用 CreateThread() 通过使用一个 void * 参数启动一个函数来创建一个线程.我将指向结构的指针作为该参数传递,并且我看到很多其他人也这样做.

In Microsoft Visual C++ I can call CreateThread() to create a thread by starting a function with one void * parameter. I pass a pointer to a struct as that parameter, and I see a lot of other people do that as well.

我的问题是,如果我传递一个指向我的结构的指针,我如何知道在调用 CreateThread() 之前结构成员是否已实际写入内存?有没有保证它们不会被缓存?例如:

My question is if I am passing a pointer to my struct how do I know if the structure members have been actually written to memory before CreateThread() was called? Is there any guarantee they won't be just cached? For example:

struct bigapple { string color; int count; } apple;
apple.count = 1;
apple.color = "red";
hThread = CreateThread( NULL, 0, myfunction, &apple, 0, NULL );

DWORD WINAPI myfunction( void *param )
{
    struct bigapple *myapple = (struct bigapple *)param;

    // how do I know that apple's struct was actually written to memory before CreateThread?
    cout << "Apple count: " << myapple->count << endl; 
}

今天下午在阅读时,我在这个网站和其他网站上看到了很多 Windows 代码,这些代码将非易失性数据传递给线程,而且似乎没有任何内存障碍或其他任何东西.我知道 C++ 或至少较旧的修订版不是线程感知"的,所以我想知道是否还有其他原因.我的猜测是编译器看到我在对 CreateThread() 的调用中传递了一个指针 &apple,因此它知道在调用之前写出 apple 的成员.

This afternoon while I was reading I saw a lot of Windows code on this website and others that passes in data that is not volatile to a thread, and there doesn't seem to be any memory barrier or anything else. I know C++ or at least older revisions are not "thread aware" so I'm wondering if maybe there's some other reason. My guess would be the compiler sees that I've passed a pointer &apple in a call to CreateThread() so it knows to write out members of apple before the call.

谢谢

推荐答案

没有.相关的 Win32 线程函数都会处理必要的内存屏障.CreateThread 之前的所有写入对新线程都是可见的.显然,在调用 CreateThread 之前,新创建的线程中的读取不能重新排序.

No. The relevant Win32 thread functions all take care of the necessary memory barriers. All writes prior to CreateThread are visible to the new thread. Obviously the reads in that newly created thread cannot be reordered before the call to CreateThread.

volatile 不会对编译器添加任何额外有用的约束,只会减慢代码速度.但实际上,与创建新线程的成本相比,thiw 并不明显.

volatile would not add any extra useful constraints on the compiler, and merely slow down the code. In practice thiw wouldn't be noticeable compared to the cost of creating a new thread, though.

这篇关于C++ - 传递给线程的数据是否应该是易失性的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆