如何在WinAPI中允许两个线程共享全局变量? [英] How to allow two threads to share a global variable in WinAPI?

查看:101
本文介绍了如何在WinAPI中允许两个线程共享全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个使用 CreateThread(),我有一个全局变量,一个线程写入该全局变量,另一个线程从该全局变量读取.

现在,根据我的理解,编译器和/或CPU可以进行各种优化,这可能意味着,例如,当我将值写入变量时,该值可以写入某些缓存中,而不能直接写入内存(因此其他线程将无法看到它).

我已阅读到可以将访问变量的代码包装在关键部分,但是解决方案

MSDN明确声明关键部分是内存障碍. https://msdn.microsoft .com/en-us/library/windows/desktop/ms686355(v = vs.85).aspx

I have two threads that are created using CreateThread(), and I have a global variable that one thread writes to, and the other thread reads from.

Now based on my understanding, the compiler and/or the CPU can do all sorts of optimizations, which could mean for example that when I write a value to the variable, the value can be written in some cache and not written directly to memory (and hence the other thread will not be able to see it).

I have read that I can wrap the code that access the variable in a critical section, but the documentation says that a critical section will only enforce mutual exclusion, and does not say anything about enforcing writing directly to memory and reading directly from memory.

Note that I do not which to use the volatile keyword, I want to know how this is done in pure WinAPI (as I could use a language other than C in a later time).

解决方案

MSDN explicitly states that critical sections are memory barriers. https://msdn.microsoft.com/en-us/library/windows/desktop/ms686355(v=vs.85).aspx

这篇关于如何在WinAPI中允许两个线程共享全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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