【发布时间】:2016-02-07 10:04:35
【问题描述】:
我在我的项目中遇到了一个问题,即需要线程之间就可以写入的资源进行通信,因此必须进行同步。但是,除了基本级别之外,我对同步一无所知。
考虑此链接中的最后一个示例:http://www.bogotobogo.com/cplusplus/C11/7_C11_Thread_Sharing_Memory.php
#include <iostream>
#include <thread>
#include <list>
#include <algorithm>
#include <mutex>
using namespace std;
// a global variable
std::list<int>myList;
// a global instance of std::mutex to protect global variable
std::mutex myMutex;
void addToList(int max, int interval)
{
// the access to this function is mutually exclusive
std::lock_guard<std::mutex> guard(myMutex);
for (int i = 0; i < max; i++) {
if( (i % interval) == 0) myList.push_back(i);
}
}
void printList()
{
// the access to this function is mutually exclusive
std::lock_guard<std::mutex> guard(myMutex);
for (auto itr = myList.begin(), end_itr = myList.end(); itr != end_itr; ++itr ) {
cout << *itr << ",";
}
}
int main()
{
int max = 100;
std::thread t1(addToList, max, 1);
std::thread t2(addToList, max, 10);
std::thread t3(printList);
t1.join();
t2.join();
t3.join();
return 0;
}
该示例演示了三个线程(两个写入者和一个读取者)如何访问公共资源(列表)。
使用了两个全局函数:一个由两个写入线程使用,一个由读取线程使用。这两个函数都使用 lock_guard 来锁定相同的资源,即列表。
现在这就是我无法理解的内容:阅读器在与两个编写器线程不同的范围内使用锁,但仍锁定相同的资源。这怎么行?我对互斥锁的有限理解非常适合编写器功能,您有两个线程使用完全相同的功能。我可以理解,在您即将进入保护区时进行检查,如果其他人已经在里面,您等待。
但是当范围不同时呢?这表明存在某种比进程本身更强大的机制,某种运行时环境阻止“迟到”线程的执行。但我认为 C++ 中没有这样的东西。所以我很茫然。
这里到底发生了什么?
【问题讨论】:
-
我想补充一点,互斥锁是atomic。希望这会有所帮助。
标签: c++ multithreading thread-safety