开发者

Explain how it works mutex

Now i'm try to learn multithreading and mutext. But i don't understand it. For example i add items to list in anotyher thread then main programm:

GMutext* lock;
g_mutex_lock (lock);
g_list_prepend(list, "Some data");
g_mutex_unlock (lock);

What happens in this case with the list? The 开发者_C百科list of added elements, as well as no access from the main thread until the g_mutex_unlock? Or i wrong understand it?

Thank you.

Thank you.


While the mutex is locked any other thread that wants to lock it will block until the mutex is unlocked by the thread currently holding the lock. This doesn't relate to the list object - if some other thread doesn't try to lock the same mutex is can try to do anything with the list and concurrent access might occur causing list corruption.

So locking the mutext is a convention. The caller must obey the convention - try to acquire the mutex lock before accessing the guarded data object. Mapping between data objects and mutexes is up to the developer here.


No, anyone accessing the list outside the mutex can still see the changes. But you shouldn't do that (usually, anyway). The point is to allow changes to effectively become atomic - you would lock the mutex everywhere that you needed to access the shared state. That effectively serializes access across threads, so each thread gets to make its changes (or read its data) knowing that nothing else is messing with the list. It's cooperative though - if you forget to lock the mutex when accessing the list, you'll run the risk of data races.


The mutex and the list are two separate objects. There is nothing stopping you from accessing the list outside of a mutex and thus not guaranteeing mutual exclusion (hence the name mutex).

You'll often see code like this:

GMutext* lock;
GList* list

void addData(string data) {
  g_mutex_lock (lock);
  g_list_prepend(list, data);
  g_mutex_unlock (lock);
}

string getData() {
  g_mutex_lock (lock);
  GList* data = g_list_first (list);
  g_list_remove(list, data);
  g_mutex_unlock (lock);
  return data;
}

This ensures that the list is always accessed safely. If another method access the list directly without using the same mutex there's no guarantee what state the list could be in (eg what data is retrieved/added).


Mutex means: Mutual exclusive. That means, the mutex object can only be accessed by one user at the same time. There are different approches how to handle, one is busy waiting, and there are semaphores. Some CPU have mutex like instructions, test and set as an atomic operation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜