且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在C中跨进程使用互斥锁

更新时间:2023-11-13 23:20:16

调用 ^ ]函数,请指定相同的名称(最后一个参数 lpName ).该函数首先尝试查找具有指定名称的互斥锁,如果存在这种互斥锁,则返回其句柄.否则,它将创建新的互斥锁.因此,调用CreateMutex(,,"MyMutex")的第一个过程将尝试找到"MyMutex",但这样做失败,然后创建互斥体"MyMutex".第二个过程的调用会发现现有对象并返回其句柄(您可以通过调用 GetLastError()函数来检查互斥体是否已打开,而不是新创建的,它应该返回ERROR_ALREADY_EXISTS代码).
还有一点要注意:选择互斥锁名称时,请决定是否要跨用户会话访问此互斥锁.当多个用户同时登录同一台计算机时,一个用户会话中的内核对象名称将在另一个会话中不可见,除非它们以"Global \"前缀开头(有关内核对象名称空间的详细信息,请参见此处 [
When you call CreateMutex[^] function in both processes, specify the same name (last parameter, lpName). This function first tries to find a mutex with specified name, and if such mutex exists, returns its handle; otherwise, it creates new mutex. So, the first process to call CreateMutex(, , "MyMutex") shall try to find "MyMutex", fail to do that and then create mutex "MyMutex". Call from the second process discovers existing object and returns its handle (you can check that mutex is opened, not newly created, by calling GetLastError() function, it should return ERROR_ALREADY_EXISTS code).
One more note: when you select mutex name, decide whether you want this mutex to be accessible across user sessions or not. When more than one user is logged in on the same computer simultaneously, kernel object''s names from one user session won''t be visible in another session unless they start with "Global\" prefix (see more about kernel object namespaces here[^])


您不能在单个进程中使用互斥锁-整个想法是它们可以跨多个进程工作.
互斥锁(互斥锁)用于实现关键部分并保护共享的可变数据结构免受并发访问.
根据定义,单个进程不能使用互斥锁,因为它没有其他访问权限可以担心...
You can''t use a mutex in a single process - the whole idea is that they work across multiple processes.
Mutexes (mutual-exclusion locks) are used to implement critical sections and protect shared mutable data structures against concurrent accesses.
By definition, a single process cannot use a mutex, because it has no other accesses to worry about...