简体   繁体   English

如何干净地实例化一个线程本身中的线程共享的全局互斥锁

[英]How to cleanly instantiate a global mutex that is shared by threads in one of the threads itself

I use GLib/GObject and am facing the following problem: 我使用GLib / GObject并面临以下问题:

I have a class my_class that will have several object instances in multiple threads during runtime, where each object will exist within a single thread (so there is a 1:1 relation between the thread and the object). 我有一个my_class类,它将在运行时在多个线程中具有多个对象实例,其中每个对象都将存在于单个线程中(因此线程与对象之间存在1:1关系)。

However, the object will access a shared resource and I need locking to protect access to that resource. 但是,对象将访问共享资源,并且我需要锁定以保护对该资源的访问。 Now, I need a global mutex (a GMutex in GLib world) instance, that is available to all threads/objects to lock onto. 现在,我需要一个全局互斥锁(GLib世界中的GMutex )实例,所有线程/对象都可以使用该实例来锁定。

My current approach is to create that mutex before the threads are spawned, and pass that global mutex along in the constructor. 我当前的方法是在生成线程之前创建该互斥锁,并在构造函数中传递该全局互斥锁。 But I don't like that approach. 但是我不喜欢这种方法。 The mutex is not of any concern of the calling code before creating the threads - it is only required for functionality by the my_class and should as such then only be part of the my_class for a clean OO design. 在创建线程之前,互斥锁与调用代码my_class ,它仅是my_class功能所my_class ,因此,对于干净的OO设计, my_class仅应是my_class一部分。

But how to create a single mutex from within my_class ? 但是如何从my_class内部创建单个互斥锁? I could create a static GMutex *global_mutex and have it as global variable, shared across all threads. 我可以创建一个static GMutex *global_mutex并将其作为全局变量,并在所有线程之间共享。 But when/how to call g_mutex_new() ? 但是何时/如何调用g_mutex_new() I'd like to have it in the constructor of my_class , but the code needs only to be run once. 我想在my_class的构造函数中使用my_class ,但是代码只需要运行一次。 To achieve that, I need locking in the first place, and I face an Chicken-Egg problem. 为了实现这一点,我首先需要锁定,并且我面临着Chicken-Egg问题。

What you want is a GStaticMutex . 您想要的是GStaticMutex Declare it as a static local variable in the thread function, and initialize it with G_STATIC_MUTEX_INIT : 在线程函数中将其声明为静态局部变量,然后使用G_STATIC_MUTEX_INIT对其进行初始化:

static GStaticMutex my_mutex = G_STATIC_MUTEX_INIT;

This declares, defines and initializes the mutex, so it can be used directly. 它声明,定义和初始化互斥锁,因此可以直接使用它。

See the example in the linked reference. 请参阅链接参考中的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM