如何在VC ++中创建锁? [英] How to create locks in VC++?

查看:393
本文介绍了如何在VC ++中创建锁?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我正在VC ++中实现一个关键部分并保护某些数组,我该如何使用VC ++中的锁来做到这一点?

Lets say I am implementing a critical section and protecting some array in VC++, how do I do it using locks in VC++?

推荐答案

您需要

  • InitializeCriticalSection 调用一次,可以从任何线程(通常是主线程)初始化锁.在对其进行任何其他操作之前,请先进行初始化.
  • EnterCriticalSection 来自任何地方的呼叫线程获取锁.如果另一个线程拥有该锁,它将阻塞直到可以获取该锁.关键部分是可重入的,这意味着即使线程已经持有该锁,它也可以成功获取该锁.
  • LeaveCriticalSection 版本锁.每个对EnterCriticalSection的调用必须与对LeaveCriticalSection的匹配调用配对.不要让异常阻止这些获取/释放调用配对.
  • DeleteCriticalSection 调用一次,可以从任何线程(通常是主线程)完成锁定.当没有线程持有该锁时,请执行此操作.调用此锁后,该锁无效,无法再尝试获取它.
    • InitializeCriticalSection Call once, from any thread, but typically the main thread, to initialize the lock. Initialize before you do anything else with it.
    • EnterCriticalSection Call from any thread to acquire the lock. If another thread has the lock, it will block until it can acquire the lock. Critical sections are re-entrant meaning a thread successfully acquires the lock even if it already holds it.
    • LeaveCriticalSection Release the lock. Each call to EnterCriticalSection must be paired with a matching call to LeaveCriticalSection. Don't let exceptions stop these acquire/release calls being paired up.
    • DeleteCriticalSection Call once, from any thread, but typically the main thread, to finalize the lock. Do this when no threads hold the lock. After you call this the lock is invalid and you can't attempt to acquire it again.

    MSDN有助于提供一个简单的示例.

    MSDN helpfully provide a trivial example.

    如果您使用的是MFC,则可能会使用

    If you are using MFC then you would probably use CCriticalSection which wraps up the Win32 critical section APIs in a class.

    关于如何使用阵列.好吧,您的线程一次只能执行一个受锁保护的代码块.您需要使用锁来阻止竞争条件,在竞争条件下,两个线程试图同时读取/写入同一内​​存位置,或者实际上是其他更细微的条件,这些条件可能会破坏您的算法.

    As for how you do it with your array. Well, your threads will only execute blocks of code protected by the lock one at a time. You need the lock to stop race conditions where two threads try to read/write to the same memory location simultaneously, or indeed other more subtle conditions that can break your algorithm.

    如果要描述数组,数组的内容以及如何对其进行操作,则可能会为您提供一些具体建议.确切地说,如何在此阵列上进行操作将与理想的同步策略有很大关系,并且在某些情况下,您可能可以使用无锁方法.

    If you were to describe the array, its contents, and how you operate on it, then it might be possible to give you some specific advice. Exactly how you operate on this array will have a large bearing on the ideal synchronisation strategy, and in certain cases you may be able to use lock-free methods.

    这篇关于如何在VC ++中创建锁?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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