21

我想从并行运行的线程中以只读方式访问基于 STL 的容器。不使用任何用户实现的锁定。以下代码的基础是正确实现该标准的 C++11。

http://gcc.gnu.org/onlinedocs/libstdc++/manual/using_concurrency.html
http://www.sgi.com/tech/stl/thread_safety.html
http://www.hpl.hp.com/personal/ Hans_Boehm/c++mm/threadsintro.html
http://www.open-std.org/jtc1/sc22/wg21/当前草案N3337,本质上是 C++11,有小错误和错别字更正)

23.2.2 容器数据竞赛 [container.requirements.dataraces]

为避免数据竞争 (17.6.5.9),实现应将以下函数视为 const:begin、end、rbegin、rend、front、back、data、find、lower_bound、upper_bound、equal_range、at 和,除了关联或无序的关联容器,operator[]。

尽管有(17.6.5.9),当同时修改同一序列中不同元素中的包含对象的内容(vector<bool> 除外)时,需要实现来避免数据竞争。

[注意:对于大小大于一的向量<int> x,x[1] = 5 和 *x.begin() = 10 可以在没有数据竞争的情况下同时执行,但是 x[0] = 5 和 * x.begin() = 10 同时执行可能会导致数据竞争。作为一般规则的一个例外,对于 vector<bool> y,y[0] = true 可能与 y[1] = true 竞争。——尾注]

17.6.5.9 避免数据竞争[res.on.data.races] 1 本节规定了实现应满足的要求,以防止数据竞争(1.10)。除非另有说明,否则每个标准库函数都应满足每个要求。实施可能会在下面指定的情况以外的情况下防止数据竞争。

2 C++ 标准库函数不应直接或间接访问可由当前线程以外的线程访问的对象 (1.10),除非通过函数的参数直接或间接访问对象,包括 this。

3 C++ 标准库函数不得直接或间接修改可由当前线程以外的线程访问的对象 (1.10),除非通过函数的非 const 参数直接或间接访问对象,包括 this。

4 [注:这意味着,例如,实现不能在没有同步的情况下将静态对象用于内部目的,因为即使在没有显式在线程之间共享对象的程序中,它也可能导致数据竞争。——尾注]

5 C++ 标准库函数不应访问通过其参数或通过其容器参数的元素间接访问的对象,除非通过调用其规范要求的那些容器元素的函数。

6 通过调用标准库容器或字符串成员函数获得的迭代器上的操作可以
访问底层容器,但不得修改它。[注意:特别是,使迭代器无效的容器操作与与该容器关联的迭代器上的操作相冲突。——尾注]

7 如果对象对用户不可见并且受到保护以防止数据竞争,则实现可以在线程之间共享它们自己的内部对象。

8 除非另有说明,否则 C++ 标准库函数应仅在当前线程内执行所有操作,前提是这些操作具有对用户可见 (1.10) 的效果。

9 [注意:如果没有可见的副作用,这允许实现并行化操作。——尾注]

结论
容器不是线程安全的!但是从多个并行线程调用容器上的const 函数是安全的。因此可以从并行线程执行只读操作而无需锁定。我对吗?

我假装他们不存在任何错误的实现,并且 C++11 标准的每个实现都是正确的。

样本:

// concurrent thread access to a stl container
// g++ -std=gnu++11 -o p_read p_read.cpp -pthread -Wall -pedantic && ./p_read
#include <iostream>
#include <iomanip>
#include <string>
#include <unistd.h>

#include <thread>
#include <mutex>

#include <map>

#include <cstdlib>
#include <ctime>
using namespace std;

// new in C++11
using str_map = map<string, string>;

// thread is new in C++11
// to_string() is new in C++11

mutex m;
const unsigned int MAP_SIZE = 10000;

void fill_map(str_map& store) {
    int key_nr;
    string mapped_value;
    string key;

    while (store.size() < MAP_SIZE) {
        // 0 - 9999
        key_nr = rand() % MAP_SIZE;

        // convert number to string
        mapped_value = to_string(key_nr);
        key = "key_" + mapped_value;

        pair<string, string> value(key, mapped_value);
        store.insert(value);
    }
}

void print_map(const str_map& store) {
    str_map::const_iterator it = store.begin();

    while (it != store.end()) {
        pair<string, string> value = *it;
        cout << left << setw(10) << value.first << right << setw(5) << value.second << "\n";
        it++;   
    }
}

void search_map(const str_map& store, int thread_nr) {
    m.lock();
    cout << "thread(" << thread_nr << ") launched\n";
    m.unlock();

    // use a straight search or poke around random
    bool straight = false;
    if ((thread_nr % 2) == 0) {
        straight = true;
    }

    int key_nr;
    string mapped_value;
    string key;
    str_map::const_iterator it;

    string first;
    string second;

    for (unsigned int i = 0; i < MAP_SIZE; i++) {

        if (straight) {
            key_nr = i;
        } else {
            // 0 - 9999, rand is not thread-safe, nrand48 is an alternative             
            m.lock();
            key_nr = rand() % MAP_SIZE;
            m.unlock();
        }

        // convert number to string
        mapped_value = to_string(key_nr);
        key = "key_" + mapped_value;

        it = store.find(key);

        // check result
        if (it != store.end()) {
            // pair
            first = it->first;
            second = it->second;

            // m.lock();
            // cout << "thread(" << thread_nr << ") " << key << ": "
            //      << right << setw(10) << first << setw(5) << second << "\n"; 
            // m.unlock();

            // check mismatch
            if (key != first || mapped_value != second) {
                m.lock();
                cerr << key << ": " << first << second << "\n"
                     << "Mismatch in thread(" << thread_nr << ")!\n";
                exit(1);

                // never reached
                m.unlock();
            }
        } else {
            m.lock();
            cerr << "Warning: key(" << key << ") not found in thread("
                 << thread_nr << ")\n";
            exit(1);

            // never reached
            m.unlock();
        }
    }
}

int main() {
    clock_t start, end;
    start = clock();

    str_map store;
    srand(0);

    fill_map(store);
    cout << "fill_map finished\n";

    // print_map(store);
    // cout << "print_map finished\n";

    // copy for check
    str_map copy_store = store;

    // launch threads
    thread t[10];
    for (int i = 0; i < 10; i++) {
        t[i] = thread(search_map, store, i);
    }

    // wait for finish
    for (int i = 0; i < 10; i++) {
        t[i].join();
    }
    cout << "search_map threads finished\n";

    if (store == copy_store) {
        cout << "equal\n";
    } else {
        cout << "not equal\n";
    }


    end = clock();
    cout << "CLOCKS_PER_SEC " << CLOCKS_PER_SEC << "\n";
    cout << "CPU-TIME START " << start << "\n";
    cout << "CPU-TIME END " << end << "\n";
    cout << "CPU-TIME END - START " << end - start << "\n";
    cout << "TIME(SEC) " << static_cast<double>(end - start) / CLOCKS_PER_SEC << "\n";

    return 0;
}

这段代码可以用GCC 4.7编译并在我的机器上运行良好。

$回声$?
$ 0

4

2 回答 2

21

来自 C++11 规范第 1.10/4 节和 1.10/21 节中的数据争用需要至少两个线程对同一组内存位置进行非原子访问,这两个线程在访问方面不同步该组内存位置,并且至少一个线程写入或修改该组内存位置中的一个元素。所以在你的情况下,如果线程只是读取,你很好......根据定义,因为没有线程写入同一组内存位置,即使没有明确的同步机制,也没有数据竞争线程。

于 2012-05-31T12:25:42.040 回答
4

Yes, you are right. You are safe as long as the thread that populates your vector finishes doing so before the reader threads start. There was a similar question recently.

于 2012-05-31T12:26:26.053 回答