Initial commit
authorJeff Preshing <filter-github@preshing.com>
Mon, 1 Feb 2016 13:09:52 +0000 (08:09 -0500)
committerJeff Preshing <filter-github@preshing.com>
Mon, 1 Feb 2016 13:09:52 +0000 (08:09 -0500)
79 files changed:
.clang-format [new file with mode: 0644]
.gitignore [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0644]
README.md [new file with mode: 0644]
cmake/AddSample.cmake [new file with mode: 0644]
cmake/JunctionProjectDefs.cmake [new file with mode: 0644]
cmake/junction_config.h.in [new file with mode: 0644]
cmake/modules/FindCDS.cmake [new file with mode: 0644]
cmake/modules/FindFolly.cmake [new file with mode: 0644]
cmake/modules/FindNBDS.cmake [new file with mode: 0644]
cmake/modules/FindTBB.cmake [new file with mode: 0644]
cmake/modules/FindTervel.cmake [new file with mode: 0644]
cmake/modules/FindTurf.cmake [new file with mode: 0644]
docs/cmake-gui.png [new file with mode: 0644]
docs/vs-solution.png [new file with mode: 0644]
junction/Averager.cpp [new file with mode: 0644]
junction/Averager.h [new file with mode: 0644]
junction/ConcurrentMap_Grampa.cpp [new file with mode: 0644]
junction/ConcurrentMap_Grampa.h [new file with mode: 0644]
junction/ConcurrentMap_LeapFrog.cpp [new file with mode: 0644]
junction/ConcurrentMap_LeapFrog.h [new file with mode: 0644]
junction/ConcurrentMap_Linear.cpp [new file with mode: 0644]
junction/ConcurrentMap_Linear.h [new file with mode: 0644]
junction/Core.h [new file with mode: 0644]
junction/MapTraits.h [new file with mode: 0644]
junction/QSBR.cpp [new file with mode: 0644]
junction/QSBR.h [new file with mode: 0644]
junction/SimpleJobCoordinator.h [new file with mode: 0644]
junction/SingleMap_Linear.h [new file with mode: 0644]
junction/details/Grampa.cpp [new file with mode: 0644]
junction/details/Grampa.h [new file with mode: 0644]
junction/details/LeapFrog.cpp [new file with mode: 0644]
junction/details/LeapFrog.h [new file with mode: 0644]
junction/details/Linear.cpp [new file with mode: 0644]
junction/details/Linear.h [new file with mode: 0644]
junction/extra/MapAdapter.h [new file with mode: 0644]
junction/extra/MemHook_NBDS.cpp [new file with mode: 0644]
junction/extra/MemHook_TBB.cpp [new file with mode: 0644]
junction/extra/impl/MapAdapter_CDS_Cuckoo.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_CDS_Michael.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Folly.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Grampa.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_LeapFrog.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Linear.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Linear_Mutex.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Linear_RWLock.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_NBDS.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Null.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_StdMap.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_TBB.h [new file with mode: 0644]
junction/extra/impl/MapAdapter_Tervel.h [new file with mode: 0644]
junction/striped/AutoResetEvent.h [new file with mode: 0644]
junction/striped/ConditionBank.cpp [new file with mode: 0644]
junction/striped/ConditionBank.h [new file with mode: 0644]
junction/striped/ConditionPair.h [new file with mode: 0644]
junction/striped/ManualResetEvent.h [new file with mode: 0644]
junction/striped/Mutex.h [new file with mode: 0644]
samples/MallocTest/CMakeLists.txt [new file with mode: 0644]
samples/MallocTest/MallocTest.cpp [new file with mode: 0644]
samples/MapCorrectnessTests/CMakeLists.txt [new file with mode: 0644]
samples/MapCorrectnessTests/MapCorrectnessTests.cpp [new file with mode: 0644]
samples/MapCorrectnessTests/TestChurn.h [new file with mode: 0644]
samples/MapCorrectnessTests/TestEnvironment.h [new file with mode: 0644]
samples/MapCorrectnessTests/TestInsertDifferentKeys.h [new file with mode: 0644]
samples/MapCorrectnessTests/TestInsertSameKeys.h [new file with mode: 0644]
samples/MapCorrectnessTests/junction_userconfig.h.in [new file with mode: 0644]
samples/MapMemoryBench/CMakeLists.txt [new file with mode: 0644]
samples/MapMemoryBench/MapMemoryBench.cpp [new file with mode: 0644]
samples/MapMemoryBench/RenderGraphs.py [new file with mode: 0644]
samples/MapMemoryBench/TestAllMaps.py [new file with mode: 0644]
samples/MapPerformanceTests/CMakeLists.txt [new file with mode: 0644]
samples/MapPerformanceTests/MapPerformanceTests.cpp [new file with mode: 0644]
samples/MapPerformanceTests/RenderGraphs.py [new file with mode: 0644]
samples/MapPerformanceTests/TestAllMaps.py [new file with mode: 0644]
samples/MapScalabilityTests/CMakeLists.txt [new file with mode: 0644]
samples/MapScalabilityTests/MapScalabilityTests.cpp [new file with mode: 0644]
samples/MapScalabilityTests/RenderGraphs.py [new file with mode: 0644]
samples/MapScalabilityTests/TestAllMaps.py [new file with mode: 0644]

diff --git a/.clang-format b/.clang-format
new file mode 100644 (file)
index 0000000..be640a0
--- /dev/null
@@ -0,0 +1,9 @@
+ColumnLimit: 130
+IndentWidth: 4
+UseTab: Never
+AccessModifierOffset: -4
+NamespaceIndentation: None
+DerivePointerAlignment: false
+PointerAlignment: Left
+SpaceAfterCStyleCast: true
+AllowShortFunctionsOnASingleLine: None
diff --git a/.gitignore b/.gitignore
new file mode 100644 (file)
index 0000000..3c10c08
--- /dev/null
@@ -0,0 +1,3 @@
+*build*/
+CMakeLists.txt.user
+*~
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0452094
--- /dev/null
@@ -0,0 +1,114 @@
+cmake_minimum_required(VERSION 2.8.5)
+
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+       # If this is the root project, issue a project() command so that
+       # the Visual Studio generator will create an .sln file.
+    set(CMAKE_CONFIGURATION_TYPES "Debug;RelWithAsserts;RelWithDebInfo" CACHE INTERNAL "Build configs")
+       project(Junction)
+    set_property(GLOBAL PROPERTY USE_FOLDERS ON)
+    include(cmake/JunctionProjectDefs.cmake)
+    ApplyTurfBuildSettings()
+elseif(NOT JUNCTION_FOUND)
+    message(FATAL_ERROR "You must include cmake/JunctionProjectDefs.cmake before adding this subdirectory")
+endif()        
+
+# Default values, can be overridden by user
+set(JUNCTION_USERCONFIG "" CACHE STRING "Optional path to additional config file (relative to root CMakeLists.txt)")
+set(JUNCTION_WITH_FOLLY FALSE CACHE BOOL "Use Folly")
+set(JUNCTION_WITH_CDS FALSE CACHE BOOL "Use CDS")
+set(JUNCTION_WITH_NBDS FALSE CACHE BOOL "Use NBDS")
+set(JUNCTION_WITH_TBB FALSE CACHE BOOL "Use TBB")
+set(JUNCTION_WITH_TERVEL FALSE CACHE BOOL "Use Tervel")
+set(JUNCTION_TRACK_GRAMPA_STATS FALSE CACHE BOOL "Enable stats in ConcurrentMap_Grampa")
+set(JUNCTION_USE_STRIPING TRUE CACHE BOOL "Allocate a fixed-size ConditionBank for striped primitives")
+
+# Initialize variables used to collect include dirs/libraries.
+set(JUNCTION_INCLUDE_DIRS "${CMAKE_CURRENT_SOURCE_DIR}" "${CMAKE_CURRENT_BINARY_DIR}/include")
+set(JUNCTION_ALL_INCLUDE_DIRS "${JUNCTION_INCLUDE_DIRS}")
+set(JUNCTION_ALL_LIBRARIES junction)
+set(JUNCTION_ALL_DLLS "")
+
+# Add turf targets
+add_subdirectory(${TURF_ROOT} turf)
+list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${TURF_INCLUDE_DIRS})
+list(APPEND JUNCTION_ALL_LIBRARIES ${TURF_ALL_LIBRARIES})
+
+# Optional: Locate Folly and append it to the list of include dirs/libraries.
+if(JUNCTION_WITH_FOLLY)
+       find_package(Folly REQUIRED)
+       list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${FOLLY_INCLUDE_DIR})
+       list(APPEND JUNCTION_ALL_LIBRARIES ${FOLLY_LIBRARIES})
+endif()
+
+# Optional: Locate CDS and append it to the list of include dirs/libraries.
+if(JUNCTION_WITH_CDS)
+    find_package(CDS REQUIRED)
+    list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${CDS_INCLUDE_DIR})
+    list(APPEND JUNCTION_ALL_LIBRARIES ${CDS_LIBRARY})
+    list(APPEND JUNCTION_ALL_DLLS ${CDS_DLL})
+endif()
+
+# Optional: Locate NBDS and append it to the list of include dirs/libraries.
+if(JUNCTION_WITH_NBDS)
+    set(NBDS_USE_TURF_HEAP FALSE CACHE BOOL "Redirect NBDS's memory allocator to use Turf")
+    find_package(NBDS REQUIRED)
+    list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${NBDS_INCLUDE_DIRS})
+    # If NBDS_USE_TURF_HEAP=1, then NBDS has dependencies on junction, so add junction to the linker
+    # command line again as needed by the GNU linker.
+    list(APPEND JUNCTION_ALL_LIBRARIES ${NBDS_LIBRARIES} junction)
+endif()
+
+# Optional: Locate Intel TBB and append it to the list of include dirs/libraries.
+if(JUNCTION_WITH_TBB)
+    set(TBB_USE_TURF_HEAP FALSE CACHE BOOL "Redirect TBB's memory allocator to use Turf")
+    find_package(TBB REQUIRED)
+    list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${TBB_INCLUDE_DIRS})
+    # If TBB_USE_TURF_HEAP=1, then TBB has dependencies on junction, so add junction to the linker
+    # command line again as needed by the GNU linker.
+    list(APPEND JUNCTION_ALL_LIBRARIES ${TBB_LIBRARIES} junction)
+endif()
+
+# Optional: Locate Tervel and append it to the list of include dirs/libraries.
+if(JUNCTION_WITH_TERVEL)
+    find_package(Tervel REQUIRED)
+    list(APPEND JUNCTION_ALL_INCLUDE_DIRS ${TERVEL_INCLUDE_DIRS})
+    list(APPEND JUNCTION_ALL_LIBRARIES ${TERVEL_LIBRARIES})
+endif()
+
+# If this is the root listfile, add all samples
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    file(GLOB children samples/*)
+    foreach(child ${children})
+        if(EXISTS "${child}/CMakeLists.txt")
+            add_subdirectory("${child}")
+        endif()
+    endforeach()
+endif()
+
+# Gather source files.
+GetFilesWithSourceGroups(GLOB_RECURSE JUNCTION_FILES ${CMAKE_CURRENT_SOURCE_DIR}/junction junction/*.cpp junction/*.h)
+
+# Configure autogenerated headers.
+ConfigureFileIfChanged(cmake/junction_config.h.in "${CMAKE_CURRENT_BINARY_DIR}/include/junction_config.h" JUNCTION_FILES)
+if(JUNCTION_USERCONFIG)
+    # Interpret JUNCTION_USERCONFIG relative to root project, in case Junction was added as a subdirectory
+    GetAbsoluteRelativeTo(absPath "${CMAKE_SOURCE_DIR}" "${JUNCTION_USERCONFIG}")
+    ConfigureFileIfChanged("${absPath}" "${CMAKE_CURRENT_BINARY_DIR}/include/junction_userconfig.h" JUNCTION_FILES)
+else()
+    WriteFileIfDifferent("// JUNCTION_USERCONFIG not set when CMake was run. This is a placeholder file.\n" "${CMAKE_CURRENT_BINARY_DIR}/include/junction_userconfig.h" JUNCTION_FILES)
+endif()
+
+# Define library target.
+add_library(junction ${JUNCTION_FILES})
+
+# Set include dirs for this library (done last, so it's not inherited by subprojects like Tervel, NBDS).
+include_directories(${JUNCTION_ALL_INCLUDE_DIRS})
+
+# Export include dirs/libraries to parent project if we were invoked using add_subdirectory().
+if(NOT CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    set(JUNCTION_INCLUDE_DIRS "${JUNCTION_INCLUDE_DIRS}" PARENT_SCOPE)
+    set(JUNCTION_ALL_INCLUDE_DIRS "${JUNCTION_ALL_INCLUDE_DIRS}" PARENT_SCOPE)
+    set(JUNCTION_ALL_LIBRARIES "${JUNCTION_ALL_LIBRARIES}" PARENT_SCOPE)
+    set(JUNCTION_ALL_DLLS "${JUNCTION_ALL_DLLS}" PARENT_SCOPE)
+endif()
+
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..74a56c2
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) 2016, Jeff Preshing
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+   list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+   this list of conditions and the following disclaimer in the documentation
+   and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
diff --git a/README.md b/README.md
new file mode 100644 (file)
index 0000000..0abbc99
--- /dev/null
+++ b/README.md
@@ -0,0 +1,91 @@
+Junction is a library of concurrent data structures in C++. It contains three hash map implementations:
+
+    junction::ConcurrentMap_Linear
+    junction::ConcurrentMap_LeapFrog
+    junction::ConcurrentMap_Grampa
+
+[CMake](https://cmake.org/) and [Turf](https://github.com/preshing/AcquireRelease) are required. See the blog post [New Concurrent Hash Maps for C++](http://preshing.com/20160201/new-concurrent-hash-maps-for-cpp/) for more information.
+
+## License
+
+Junction uses the Simplified BSD License. You can use the source code freely in any project, including commercial applications, as long as you give credit by publishing the contents of the `LICENSE` file in your documentation somewhere.
+
+## Getting Started
+
+If you just want to get the code and look around, start by cloning Junction and Turf into adjacent folders, then run CMake on Junction's `CMakeLists.txt`. You'll want to pass different arguments to `cmake` depending on your platform and IDE.
+
+    $ git clone https://github.com/preshing/junction.git
+    $ git clone https://github.com/preshing/turf.git
+    $ cd junction
+    $ mkdir build
+    $ cd build
+    $ cmake <additional options> ..
+
+On Unix-like environments, `cmake` will generate a Makefile by default. On Windows, it will create a Visual Studio solution. To use a specific version of Visual Studio:
+
+    $ cmake -G "Visual Studio 14 2015" ..
+
+To generate an Xcode project on OS X:
+
+    $ cmake -G "Xcode" ..
+
+To generate an Xcode project for iOS:
+
+    $ cmake -G "Xcode" -DCMAKE_TOOLCHAIN_FILE=../../turf/cmake/toolchains/iOS.cmake ..
+
+The generated build system will contain separate targets for Junction, Turf, and some sample applications.
+
+[[https://github.com/preshing/junction/docs/vs-solution.png]]
+
+Alternatively, you can run CMake on a specific sample only:
+
+    $ cd junction/samples/MapCorrectnessTests
+    $ mkdir build
+    $ cd build
+    $ cmake <additional options> ..
+
+## Adding Junction to Your Project
+
+There are several ways to add Junction to your own C++ project.
+
+1. Add Junction as a build target in an existing CMake-based project.
+2. Use CMake to build Junction and Turf, then link the static libraries into your own project.
+3. Grab only the source files you need from Junction, copy them to your project and hack them until they build correctly.
+
+Some developers will prefer approach #3, but I encourage you to try approach #1 or #2 instead. It will be easier to grab future updates that way. There are plenty of files in Junction (and Turf) that you don't really need, but it won't hurt to keep them on your hard drive either. And if you link Junction statically, the linker will exclude the parts that aren't used.
+
+### Adding to an Existing CMake Project
+
+If your project is already based on CMake, clone the Junction and Turf source trees somewhere, then call `add_subdirectory` on Junction's root folder from your own CMake script. This will add both Junction and Turf targets to your build system.
+
+If you use Git, you can add the Junction and Turf repositories as submodules. Otherwise, you can just copy the Junction and Turf source trees to your repository.
+
+[FIXME: Create a repository with a sample project that demonstrates this.]
+
+### Building the Libraries Separately
+
+Generate Junction's build system using the steps described in the *Getting Started* section, then use it to build the libraries you need. Add these to your own build system. Make sure to generate static libraries to avoid linking parts of the library that aren't needed.
+
+[FIXME: Use CMake's install feature to generate a clean output tree, so users don't have to fiddle with include and library paths too much.]
+
+## Configuration
+
+When you first run CMake on Junction, Turf will detect the capabilities of your compiler and write the results to a file in the build tree named `include/turf_config.h`. Similarly, Junction will write `include/junction_config.h` to the build tree. You can modify the contents of those files by setting variables when CMake runs. This can be done by passing additional options to `cmake`, or by using an interactive GUI such as `cmake-gui` or `ccmake`.
+
+For example, to configure Turf to use the C++11 standard library, you can set the `TURF_PREFER_CPP11` variable on the command line:
+
+    $ cmake -DTURF_PREFER_CPP11=1 ..
+
+Or, using the CMake GUI:
+
+[[https://github.com/preshing/junction/docs/cmake-gui.png]]
+
+Many header files in Turf, and some in Junction, are configurable using preprocessor definitions. For example, `turf/Thread.h` will switch between `turf::Thread` implementations depending on the values of `TURF_IMPL_THREAD_PATH` and `TURF_IMPL_THREAD_TYPE`. If those macros are not defined, they will be set to default values based on information from the environment. You can set them directly by providing your own header file and passing it in the `TURF_USERCONFIG` variable when CMake runs. You can place this file anywhere; CMake will copy it to Turf's build tree right next to `include/turf_config.h`.
+
+    $ cmake -DTURF_USERCONFIG=path/to/custom/turf_userconfig.h.in ..
+
+The `JUNCTION_USERCONFIG` variable works in a similar way. As an example, take a look at the Python script `junction/samples/MapScalabilityTests/TestAllMaps.py`. This script invokes `cmake` several times, passing a different `junction_userconfig.h.in` file each time. That's how it builds the same test application using different map implementations.
+
+## Feedback
+
+If you have any feedback on improving these steps, feel free to [open an issue](https://github.com/preshing/junction/issues) on GitHub, or send a direct message using the [contact form](http://preshing.com/contact/) on my blog.
diff --git a/cmake/AddSample.cmake b/cmake/AddSample.cmake
new file mode 100644 (file)
index 0000000..434cf91
--- /dev/null
@@ -0,0 +1,37 @@
+#---------------------------------------------------------------------------
+# This script is included from the CMakeLists.txt (listfile) of sample applications.
+#---------------------------------------------------------------------------
+
+if(NOT DEFINED PROJECT_NAME)
+    message(FATAL_ERROR "project() should be called before including \"${CMAKE_CURRENT_LIST_FILE}\".")
+endif()
+if(NOT DEFINED SAMPLE_NAME)
+    message(FATAL_ERROR "SAMPLE_NAME should be set before including \"${CMAKE_CURRENT_LIST_FILE}\".")
+endif()
+
+# Were we included from the root listfile?
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    # Yes, it's the root.
+    include("${CMAKE_CURRENT_LIST_DIR}/JunctionProjectDefs.cmake")
+    ApplyTurfBuildSettings()
+    add_subdirectory(${JUNCTION_ROOT} junction)
+elseif(NOT JUNCTION_FOUND)
+    # No, it was added from a parent listfile (via add_subdirectory).
+    # The parent is responsible for finding Junction before adding the sample.
+    # (Or, Junction's listfile is the root, in which case Junction is already found.)
+    message(FATAL_ERROR "JUNCTION_FOUND should already be set when \"${CMAKE_CURRENT_SOURCE_FILE}\" is not the root listfile.")
+endif()
+
+# Define executable target.
+set(MACOSX_BUNDLE_GUI_IDENTIFIER "com.mycompany.\${PRODUCT_NAME:identifier}")
+SET(CMAKE_INSTALL_RPATH_USE_LINK_PATH TRUE)
+GetFilesWithSourceGroups(GLOB SAMPLE_FILES ${CMAKE_CURRENT_SOURCE_DIR} *)
+add_executable(${SAMPLE_NAME} MACOSX_BUNDLE ${SAMPLE_FILES})
+set_target_properties(${SAMPLE_NAME} PROPERTIES XCODE_ATTRIBUTE_CODE_SIGN_IDENTITY "iPhone Developer")
+set_target_properties(${SAMPLE_NAME} PROPERTIES FOLDER samples)
+install(TARGETS ${SAMPLE_NAME} DESTINATION bin)
+
+# Set include dirs and libraries
+include_directories(${JUNCTION_ALL_INCLUDE_DIRS})
+target_link_libraries(${SAMPLE_NAME} ${JUNCTION_ALL_LIBRARIES})
+AddDLLCopyStep(${SAMPLE_NAME} ${JUNCTION_ALL_DLLS})
diff --git a/cmake/JunctionProjectDefs.cmake b/cmake/JunctionProjectDefs.cmake
new file mode 100644 (file)
index 0000000..cdbe6e8
--- /dev/null
@@ -0,0 +1,17 @@
+# Add cmake/modules to module search path, so subsequent find_package() commands will work.
+list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/modules")
+
+# FIXME: Implement FindJunction.cmake that other projects can use
+# If this script was invoked from FindJunction.cmake, JUNCTION_ROOT should already be set.
+if(NOT DEFINED JUNCTION_ROOT)
+    get_filename_component(JUNCTION_ROOT ${CMAKE_CURRENT_LIST_DIR}/.. ABSOLUTE)
+endif()
+
+set(JUNCTION_FOUND TRUE)
+set(JUNCTION_INCLUDE_DIRS ${JUNCTION_ROOT})
+
+# Find Turf
+if(NOT TURF_FOUND)
+    set(TURF_WITH_EXCEPTIONS FALSE CACHE BOOL "Enable compiler support for C++ exceptions")
+    find_package(Turf REQUIRED)
+endif()
diff --git a/cmake/junction_config.h.in b/cmake/junction_config.h.in
new file mode 100644 (file)
index 0000000..37dcd70
--- /dev/null
@@ -0,0 +1,11 @@
+#cmakedefine01 JUNCTION_WITH_FOLLY
+#cmakedefine01 JUNCTION_WITH_CDS
+#cmakedefine01 JUNCTION_WITH_NBDS
+#cmakedefine01 JUNCTION_WITH_TBB
+#cmakedefine01 JUNCTION_WITH_TERVEL
+#cmakedefine01 NBDS_USE_TURF_HEAP
+#cmakedefine01 TBB_USE_TURF_HEAP
+#cmakedefine01 JUNCTION_TRACK_GRAMPA_STATS
+#cmakedefine01 JUNCTION_USE_STRIPING
+
+#include "junction_userconfig.h"
diff --git a/cmake/modules/FindCDS.cmake b/cmake/modules/FindCDS.cmake
new file mode 100644 (file)
index 0000000..c56cb1a
--- /dev/null
@@ -0,0 +1,25 @@
+#FIXME: Deal with builds from different versions of Visual Studio
+if(NOT CDS_ROOT)
+    find_path(CDS_ROOT NAMES cds/init.h PATHS
+        "${CMAKE_CURRENT_SOURCE_DIR}/../libcds"
+        "${CMAKE_SOURCE_DIR}/../libcds"
+        "${CMAKE_CURRENT_LIST_DIR}/../../../libcds"
+        C:/Jeff/libcds-master)  # FIXME: Remove this one.
+endif()
+
+find_path(CDS_INCLUDE_DIR cds/init.h ${CDS_ROOT})
+if(WIN32) #FIXME: CygWin
+    find_library(CDS_LIBRARY libcds-x86-vcv140.lib "${CDS_ROOT}/bin/vc.v140/Win32")
+    find_file(CDS_DLL libcds-x86-vcv140.dll "${CDS_ROOT}/bin/vc.v140/Win32")
+else()
+    find_library(CDS_LIBRARY cds "${CDS_ROOT}/bin/gcc-x86-linux-0" "${CDS_ROOT}/bin/gcc-amd64-linux-0")
+endif()
+
+if(CDS_LIBRARY AND CDS_INCLUDE_DIR)
+    set(CDS_FOUND TRUE)
+else()
+    message("Can't find CDS!")
+    if(CDS_FIND_REQUIRED)
+        message(FATAL_ERROR "Missing required package CDS")
+    endif()
+endif()
diff --git a/cmake/modules/FindFolly.cmake b/cmake/modules/FindFolly.cmake
new file mode 100644 (file)
index 0000000..7d4b3f7
--- /dev/null
@@ -0,0 +1,9 @@
+include(FindPackageHandleStandardArgs)
+
+find_library(FOLLY_LIBRARY folly)
+find_library(GLOG_LIBRARY glog)
+find_path(FOLLY_INCLUDE_DIR "folly/String.h")
+
+set(FOLLY_LIBRARIES ${FOLLY_LIBRARY} ${GLOG_LIBRARY})
+
+FIND_PACKAGE_HANDLE_STANDARD_ARGS(Folly REQUIRED_ARGS FOLLY_INCLUDE_DIR FOLLY_LIBRARIES)
diff --git a/cmake/modules/FindNBDS.cmake b/cmake/modules/FindNBDS.cmake
new file mode 100644 (file)
index 0000000..a79d46a
--- /dev/null
@@ -0,0 +1,37 @@
+include("${TURF_ROOT}/cmake/Macros.cmake")
+
+find_path(NBDS_ROOT NAMES
+          include/hashtable.h
+          include/map.h
+          include/rcu.h
+          include/common.h
+          PATHS
+          ~/nbds)
+if(NBDS_ROOT)
+    set(NBDS_FOUND TRUE)
+    set(NBDS_INCLUDE_DIRS ${NBDS_ROOT}/include)
+    GetFilesWithSourceGroups(GLOB_RECURSE NBDS_FILES ${NBDS_ROOT} ${NBDS_ROOT}/include/*
+        ${NBDS_ROOT}/runtime/runtime.c
+        ${NBDS_ROOT}/runtime/rcu.c
+        ${NBDS_ROOT}/runtime/lwt.c
+        ${NBDS_ROOT}/runtime/random.c
+        ${NBDS_ROOT}/datatype/nstring.c
+        ${NBDS_ROOT}/runtime/hazard.c
+        ${NBDS_ROOT}/map/map.c
+        ${NBDS_ROOT}/map/list.c
+        ${NBDS_ROOT}/map/skiplist.c
+        ${NBDS_ROOT}/map/hashtable.c)
+    if(NBDS_USE_TURF_HEAP)
+        add_definitions(-DUSE_SYSTEM_MALLOC=1)
+    else()
+        GetFilesWithSourceGroups(GLOB NBDS_FILES ${NBDS_ROOT} ${NBDS_ROOT}/runtime/mem.c)
+    endif()
+    # FIXME: This is hacky because it relies on inheriting the same include_directories() as Junction
+    add_library(NBDS ${NBDS_FILES})
+    set(NBDS_LIBRARIES NBDS)
+else()
+    message("Can't find NBDS!")
+    if(NBDS_FIND_REQUIRED)
+        message(FATAL_ERROR "Missing required package NBDS")
+    endif()
+endif()
diff --git a/cmake/modules/FindTBB.cmake b/cmake/modules/FindTBB.cmake
new file mode 100644 (file)
index 0000000..819e9d8
--- /dev/null
@@ -0,0 +1,221 @@
+# The MIT License (MIT)
+#
+# Copyright (c) 2015 Justus Calvin
+# 
+# Permission is hereby granted, free of charge, to any person obtaining a copy
+# of this software and associated documentation files (the "Software"), to deal
+# in the Software without restriction, including without limitation the rights
+# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+# copies of the Software, and to permit persons to whom the Software is
+# furnished to do so, subject to the following conditions:
+# 
+# The above copyright notice and this permission notice shall be included in all
+# copies or substantial portions of the Software.
+# 
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+# SOFTWARE.
+
+#
+# FindTBB
+# -------
+#
+# Find TBB include directories and libraries.
+#
+# Usage:
+#
+#  find_package(TBB [major[.minor]] [EXACT]
+#               [QUIET] [REQUIRED]
+#               [[COMPONENTS] [components...]]
+#               [OPTIONAL_COMPONENTS components...]) 
+#
+# where the allowed components are tbbmalloc and tbb_preview. Users may modify 
+# the behavior of this module with the following variables:
+#
+# * TBB_ROOT_DIR          - The base directory the of TBB installation.
+# * TBB_INCLUDE_DIR       - The directory that contains the TBB headers files.
+# * TBB_LIBRARY           - The directory that contains the TBB library files.
+# * TBB_<library>_LIBRARY - The path of the TBB the corresponding TBB library. 
+#                           These libraries, if specified, override the 
+#                           corresponding library search results, where <library>
+#                           may be tbb, tbb_debug, tbbmalloc, tbbmalloc_debug,
+#                           tbb_preview, or tbb_preview_debug.
+# * TBB_USE_DEBUG_BUILD   - The debug version of tbb libraries, if present, will
+#                           be used instead of the release version.
+#
+# Users may modify the behavior of this module with the following environment
+# variables:
+#
+# * TBB_INSTALL_DIR 
+# * TBBROOT
+# * LIBRARY_PATH
+#
+# This module will set the following variables:
+#
+# * TBB_FOUND             - Set to false, or undefined, if we haven’t found, or
+#                           don’t want to use TBB.
+# * TBB_<component>_FOUND - If False, optional <component> part of TBB sytem is
+#                           not available.
+# * TBB_VERSION           - The full version string
+# * TBB_VERSION_MAJOR     - The major version
+# * TBB_VERSION_MINOR     - The minor version
+# * TBB_INTERFACE_VERSION - The interface version number defined in 
+#                           tbb/tbb_stddef.h.
+# * TBB_<library>_LIBRARY_RELEASE - The path of the TBB release version of 
+#                           <library>, where <library> may be tbb, tbb_debug,
+#                           tbbmalloc, tbbmalloc_debug, tbb_preview, or 
+#                           tbb_preview_debug.
+# * TBB_<library>_LIBRARY_DEGUG - The path of the TBB release version of 
+#                           <library>, where <library> may be tbb, tbb_debug,
+#                           tbbmalloc, tbbmalloc_debug, tbb_preview, or 
+#                           tbb_preview_debug.
+#
+# The following varibles should be used to build and link with TBB:
+#
+# * TBB_INCLUDE_DIRS - The include directory for TBB.
+# * TBB_LIBRARIES    - The libraries to link against to use TBB.
+# * TBB_DEFINITIONS  - Definitions to use when compiling code that uses TBB.
+
+include(FindPackageHandleStandardArgs)
+
+if(NOT TBB_FOUND)
+
+  ##################################
+  # Check the build type
+  ##################################
+  
+  if(NOT DEFINED TBB_USE_DEBUG_BUILD)
+    if(CMAKE_BUILD_TYPE MATCHES "[Debug|DEBUG|debug|RelWithDebInfo|RELWITHDEBINFO|relwithdebinfo]")
+      set(TBB_USE_DEBUG_BUILD FALSE)
+    else()
+      set(TBB_USE_DEBUG_BUILD FALSE)
+    endif()
+  endif()
+  
+  ##################################
+  # Set the TBB search directories
+  ##################################
+  
+  # Define search paths based on user input and environment variables
+  set(TBB_SEARCH_DIR ${TBB_ROOT_DIR} $ENV{TBB_INSTALL_DIR} $ENV{TBBROOT})
+  
+  # Define the search directories based on the current platform
+  if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
+    set(TBB_DEFAULT_SEARCH_DIR "C:/Program Files/Intel/TBB"
+                               "C:/Program Files (x86)/Intel/TBB")
+    # TODO: Set the proper suffix paths based on compiler introspection.
+  
+  elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin")
+    # OS X
+    set(TBB_DEFAULT_SEARCH_DIR "/opt/intel/tbb")
+    
+    # TODO: Check to see which C++ library is being used by the compiler.
+    if(NOT ${CMAKE_SYSTEM_VERSION} VERSION_LESS 13.0)
+      # The default C++ library on OS X 10.9 and later is libc++
+      set(TBB_LIB_PATH_SUFFIX "lib/libc++")
+    else()
+      set(TBB_LIB_PATH_SUFFIX "lib")
+    endif()
+  elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux")
+    # Linux
+    set(TBB_DEFAULT_SEARCH_DIR "/opt/intel/tbb")
+    
+    # TODO: Check compiler version to see the suffix should be <arch>/gcc4.1 or
+    #       <arch>/gcc4.1. For now, assume that the compiler is more recent than
+    #       gcc 4.4.x or later.
+    if(CMAKE_SYSTEM_PROCESSOR STREQUAL "x86_64")
+      set(TBB_LIB_PATH_SUFFIX "lib/intel64/gcc4.4")
+    elseif(CMAKE_SYSTEM_PROCESSOR MATCHES "^i.86$")
+      set(TBB_LIB_PATH_SUFFIX "lib/ia32/gcc4.4")
+    endif()
+  endif()
+  
+  ##################################
+  # Find the TBB include dir
+  ##################################
+  
+  find_path(TBB_INCLUDE_DIRS tbb/tbb.h
+      HINTS ${TBB_INCLUDE_DIR} ${TBB_SEARCH_DIR}
+      PATHS ${TBB_DEFAULT_SEARCH_DIR}
+      PATH_SUFFIXES include)
+  if(TBB_INCLUDE_DIR)
+    set(TBB_INCLUDE_DIRS ${TBB_INCLUDE_DIR})  # Set it directly!!
+  endif()
+
+  ##################################
+  # Find TBB components
+  ##################################
+
+  # Find each component
+  foreach(_comp tbb_preview tbbmalloc tbb)
+    # Search for the libraries
+    find_library(TBB_${_comp}_LIBRARY_RELEASE ${_comp}
+        HINTS ${TBB_LIBRARY} ${TBB_SEARCH_DIR}
+        PATHS ${TBB_DEFAULT_SEARCH_DIR}
+        PATH_SUFFIXES "${TBB_LIB_PATH_SUFFIX}")
+
+    find_library(TBB_${_comp}_LIBRARY_DEBUG ${_comp}_debug
+        HINTS ${TBB_LIBRARY} ${TBB_SEARCH_DIR}
+        PATHS ${TBB_DEFAULT_SEARCH_DIR} ENV LIBRARY_PATH
+        PATH_SUFFIXES "${TBB_LIB_PATH_SUFFIX}")
+    
+    # Set the library to be used for the component
+    if(NOT TBB_${_comp}_LIBRARY)
+      if(TBB_USE_DEBUG_BUILD AND TBB_${_comp}_LIBRARY_DEBUG)
+        set(TBB_${_comp}_LIBRARY "${TBB_${_comp}_LIBRARY_DEBUG}")
+      elseif(TBB_${_comp}_LIBRARY_RELEASE)
+        set(TBB_${_comp}_LIBRARY "${TBB_${_comp}_LIBRARY_RELEASE}")
+      elseif(TBB_${_comp}_LIBRARY_DEBUG)
+        set(TBB_${_comp}_LIBRARY "${TBB_${_comp}_LIBRARY_DEBUG}")
+      endif()
+    endif()
+    
+    # Set the TBB library list and component found variables
+    if(TBB_${_comp}_LIBRARY)
+      list(APPEND TBB_LIBRARIES "${TBB_${_comp}_LIBRARY}")
+      set(TBB_${_comp}_FOUND TRUE)
+    else()
+      set(TBB_${_comp}_FOUND FALSE)
+    endif()
+    
+    mark_as_advanced(TBB_${_comp}_LIBRARY_RELEASE)
+    mark_as_advanced(TBB_${_comp}_LIBRARY_DEBUG)
+    mark_as_advanced(TBB_${_comp}_LIBRARY)
+    
+  endforeach()
+  
+  ##################################
+  # Set compile flags
+  ##################################
+  
+  if(TBB_tbb_LIBRARY MATCHES "debug")
+    set(TBB_DEFINITIONS "-DTBB_USE_DEBUG=1")
+  endif()
+  
+  ##################################
+  # Set version strings
+  ##################################
+  
+  if(TBB_INCLUDE_DIRS)
+    file(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _tbb_version_file)
+    string(REGEX REPLACE ".*#define TBB_VERSION_MAJOR ([0-9]+).*" "\\1"
+            TBB_VERSION_MAJOR "${_tbb_version_file}")
+    string(REGEX REPLACE ".*#define TBB_VERSION_MINOR ([0-9]+).*" "\\1"
+            TBB_VERSION_MINOR "${_tbb_version_file}")
+    string(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1"
+            TBB_INTERFACE_VERSION "${_tbb_version_file}")
+    set(TBB_VERSION "${TBB_VERSION_MAJOR}.${TBB_VERSION_MINOR}")
+  endif()
+  
+  find_package_handle_standard_args(TBB 
+      REQUIRED_VARS TBB_INCLUDE_DIRS TBB_LIBRARIES
+      HANDLE_COMPONENTS
+      VERSION_VAR TBB_VERSION)
+  
+  mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARIES)
+
+endif()
diff --git a/cmake/modules/FindTervel.cmake b/cmake/modules/FindTervel.cmake
new file mode 100644 (file)
index 0000000..8aaa404
--- /dev/null
@@ -0,0 +1,17 @@
+include("${TURF_ROOT}/cmake/Macros.cmake")
+
+find_path(TERVEL_ROOT NAMES tervel/containers/wf/hash-map/wf_hash_map.h PATHS
+          ~/tervel-library)
+if(TERVEL_ROOT)
+    set(TERVEL_FOUND TRUE)
+    set(TERVEL_INCLUDE_DIRS ${TERVEL_ROOT})
+    GetFilesWithSourceGroups(GLOB_RECURSE TERVEL_FILES ${TERVEL_ROOT} ${TERVEL_ROOT}/tervel/containers/* ${TERVEL_ROOT}/tervel/util/*)
+    # FIXME: This is hacky because it relies on inheriting the same include_directories() as Junction
+    add_library(Tervel ${TERVEL_FILES})
+    set(TERVEL_LIBRARIES Tervel)
+else()
+    message("Can't find Tervel!")
+    if(Tervel_FIND_REQUIRED)
+        message(FATAL_ERROR "Missing required package Tervel")
+    endif()
+endif()
diff --git a/cmake/modules/FindTurf.cmake b/cmake/modules/FindTurf.cmake
new file mode 100644 (file)
index 0000000..2f97d4d
--- /dev/null
@@ -0,0 +1,27 @@
+#----------------------------------------------
+# When Turf is found, it's basically as if TurfProjectDefs.cmake was included.
+#
+# Later, this might find binary packages too.
+#
+# Sets:
+#    TURF_FOUND
+#    TURF_ROOT - the root folder
+#    TURF_INCLUDE_DIRS - pass to include_directories()
+#    AddTurfTarget() - call this to actually add the target
+#
+# You'll want to set the compiler options before calling AddTurfTarget().
+#----------------------------------------------
+
+find_path(TURF_ROOT NAMES "CMakeLists.txt" "cmake/TurfProjectDefs.cmake" PATHS
+    "${CMAKE_CURRENT_SOURCE_DIR}/../turf"
+    "${CMAKE_SOURCE_DIR}/../turf"
+    "${CMAKE_CURRENT_LIST_DIR}/../../../turf")
+
+if(TURF_ROOT)
+    include("${TURF_ROOT}/cmake/TurfProjectDefs.cmake")
+else()
+    message("Can't find Turf!")
+    if(Turf_FIND_REQUIRED)
+        message(FATAL_ERROR "Missing required package Turf")
+    endif()
+endif()
diff --git a/docs/cmake-gui.png b/docs/cmake-gui.png
new file mode 100644 (file)
index 0000000..ebf0403
Binary files /dev/null and b/docs/cmake-gui.png differ
diff --git a/docs/vs-solution.png b/docs/vs-solution.png
new file mode 100644 (file)
index 0000000..5382993
Binary files /dev/null and b/docs/vs-solution.png differ
diff --git a/junction/Averager.cpp b/junction/Averager.cpp
new file mode 100644 (file)
index 0000000..8ee0d00
--- /dev/null
@@ -0,0 +1,30 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <junction/Averager.h>
+#include <math.h>
+
+namespace junction {
+
+double Averager::getStdDev() {
+    finalize();
+    double avg = getAverage();
+    double dev = 0;
+    for (ureg i = 0; i < m_values.size(); i++) {
+        double diff = m_values[i] - avg;
+        dev += diff * diff;
+    }
+    return sqrt(dev / m_values.size());
+}
+
+} // namespace junction
diff --git a/junction/Averager.h b/junction/Averager.h
new file mode 100644 (file)
index 0000000..0c30fb2
--- /dev/null
@@ -0,0 +1,63 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_AVERAGER_H
+#define JUNCTION_AVERAGER_H
+
+#include <junction/Core.h>
+#include <vector>
+#include <algorithm>
+
+namespace junction {
+
+class Averager {
+private:
+    std::vector<double> m_values;
+    bool m_finalized;
+
+public:
+    Averager() : m_finalized(false) {
+    }
+
+    void add(double value) {
+        TURF_ASSERT(!m_finalized);
+        m_values.push_back(value);
+    }
+
+    ureg getNumValues() const {
+        return m_values.size();
+    }
+
+    void finalize(ureg bestValueCount = 0) {
+        if (!m_finalized) {
+            std::sort(m_values.begin(), m_values.end());
+            if (bestValueCount)
+                m_values.resize(bestValueCount);
+            m_finalized = true;
+        }
+    }
+
+    double getAverage() {
+        finalize();
+        double sum = 0;
+        for (ureg i = 0; i < m_values.size(); i++) {
+            sum += m_values[i];
+        }
+        return sum / m_values.size();
+    }
+
+    double getStdDev();
+};
+
+} // namespace junction
+
+#endif // JUNCTION_AVERAGER_H
diff --git a/junction/ConcurrentMap_Grampa.cpp b/junction/ConcurrentMap_Grampa.cpp
new file mode 100644 (file)
index 0000000..2acb10f
--- /dev/null
@@ -0,0 +1,47 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/ConcurrentMap_Grampa.h>
+
+namespace junction {
+    
+TURF_TRACE_DEFINE_BEGIN(ConcurrentMap_Grampa, 27) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[locateTable] flattree lookup redirected")
+TURF_TRACE_DEFINE("[createInitialTable] race to create initial table")
+TURF_TRACE_DEFINE("[publishTableMigration] called")
+TURF_TRACE_DEFINE("[publishTableMigration] replacing single root with single root")
+TURF_TRACE_DEFINE("[publishTableMigration] replacing flattree with single root")
+TURF_TRACE_DEFINE("[publishTableMigration] replacing single root with flattree")
+TURF_TRACE_DEFINE("[publishTableMigration] publishing subtree to existing flattree")
+TURF_TRACE_DEFINE("[publishTableMigration] existing flattree too small")
+TURF_TRACE_DEFINE("[publishTableMigration] redirected")
+TURF_TRACE_DEFINE("[publishTableMigration] recovering from partial publish")
+TURF_TRACE_DEFINE("[Mutator] find constructor called")
+TURF_TRACE_DEFINE("[Mutator] find was redirected")
+TURF_TRACE_DEFINE("[Mutator] insert constructor called")
+TURF_TRACE_DEFINE("[Mutator] insert was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] called")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] exchanged Value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] racing write inserted new value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was re-redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] overflow after redirect")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] called")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was re-redirected")
+TURF_TRACE_DEFINE("[get] called")
+TURF_TRACE_DEFINE("[get] was redirected")
+TURF_TRACE_DEFINE_END(ConcurrentMap_Grampa, 27)
+
+} // namespace junction
diff --git a/junction/ConcurrentMap_Grampa.h b/junction/ConcurrentMap_Grampa.h
new file mode 100644 (file)
index 0000000..d7fa979
--- /dev/null
@@ -0,0 +1,571 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_CONCURRENTMAP_GRAMPA_H
+#define JUNCTION_CONCURRENTMAP_GRAMPA_H
+
+#include <junction/Core.h>
+#include <junction/details/Grampa.h>
+#include <junction/QSBR.h>
+#include <turf/Heap.h>
+#include <turf/Trace.h>
+
+namespace junction {
+
+TURF_TRACE_DECLARE(ConcurrentMap_Grampa, 27)
+
+template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V>>
+class ConcurrentMap_Grampa {
+public:
+    typedef K Key;
+    typedef V Value;
+    typedef KT KeyTraits;
+    typedef VT ValueTraits;
+    typedef typename turf::util::BestFit<Key>::Unsigned Hash;
+    typedef details::Grampa<ConcurrentMap_Grampa> Details;
+
+private:
+    turf::Atomic<uptr> m_root;
+
+    bool locateTable(typename Details::Table*& table, ureg& sizeMask, Hash hash) {
+        ureg root = m_root.load(turf::Consume);
+        if (root & 1) {
+            typename Details::FlatTree* flatTree = (typename Details::FlatTree*) (root & ~ureg(1));
+            for (;;) {
+                ureg leafIdx = (hash >> flatTree->safeShift);
+                table = flatTree->getTables()[leafIdx].load(turf::Relaxed);
+                if (ureg(table) != Details::RedirectFlatTree) {
+                    sizeMask = (Details::LeafSize - 1);
+                    return true;
+                }
+                TURF_TRACE(ConcurrentMap_Grampa, 0, "[locateTable] flattree lookup redirected", uptr(flatTree), uptr(leafIdx));
+                typename Details::FlatTreeMigration* migration = Details::getExistingFlatTreeMigration(flatTree);
+                migration->run();
+                migration->m_completed.wait();
+                flatTree = migration->m_destination;
+            }
+        } else {
+            if (!root)
+                return false;
+            table = (typename Details::Table*) root;
+            sizeMask = table->sizeMask;
+            return true;
+        }
+    }
+
+    void createInitialTable(ureg initialSize) {
+        if (!m_root.load(turf::Relaxed)) {
+            // This could perform DCLI, but let's avoid needing a mutex instead.
+            typename Details::Table* table = Details::Table::create(initialSize, 0, sizeof(Hash) * 8);
+            if (m_root.compareExchange(uptr(NULL), uptr(table), turf::Release)) {
+                TURF_TRACE(ConcurrentMap_Grampa, 1, "[createInitialTable] race to create initial table", uptr(this), 0);
+                table->destroy();
+            }
+        }
+    }
+
+public:
+    ConcurrentMap_Grampa(ureg initialSize = 0) : m_root(uptr(NULL)) {
+        // FIXME: Support initialSize argument
+        TURF_UNUSED(initialSize);
+    }
+
+    ~ConcurrentMap_Grampa() {
+        ureg root = m_root.loadNonatomic();
+        if (root & 1) {
+            typename Details::FlatTree* flatTree = (typename Details::FlatTree*) (root & ~ureg(1));
+            ureg size = (Hash(-1) >> flatTree->safeShift) + 1;
+            typename Details::Table* lastTableGCed = NULL;
+            for (ureg i = 0; i < size; i++) {
+                typename Details::Table* t = flatTree->getTables()[i].loadNonatomic();
+                TURF_ASSERT(ureg(t) != Details::RedirectFlatTree);
+                if (t != lastTableGCed) {
+                    t->destroy();
+                    lastTableGCed = t;
+                }
+            }
+            flatTree->destroy();
+        } else if (root) {
+            typename Details::Table* t = (typename Details::Table*) root;
+            t->destroy();
+        }
+    }
+
+    // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
+    // after all the threads participating in the migration have completed their work.
+    // There are no racing writes to the same range of hashes.
+    void publishTableMigration(typename Details::TableMigration* migration) {
+        TURF_TRACE(ConcurrentMap_Grampa, 2, "[publishTableMigration] called", uptr(migration), 0);
+        if (migration->m_safeShift == 0) {
+            // This TableMigration replaces the entire map with a single table.
+            TURF_ASSERT(migration->m_baseHash == 0);
+            TURF_ASSERT(migration->m_numDestinations == 1);
+            ureg oldRoot = m_root.loadNonatomic();  // There are no racing writes to m_root.
+            // Store the single table in m_root directly.
+            typename Details::Table* newTable = migration->getDestinations()[0];
+            m_root.store(uptr(newTable), turf::Release);   // Make table contents visible
+            newTable->isPublished.signal();
+            if ((oldRoot & 1) == 0) {
+                TURF_TRACE(ConcurrentMap_Grampa, 3, "[publishTableMigration] replacing single root with single root", uptr(migration), 0);
+                // If oldRoot is a table, it must be the original source of the migration.
+                TURF_ASSERT((typename Details::Table*) oldRoot == migration->getSources()[0].table);
+                // Don't GC it here. The caller will GC it since it's a source of the TableMigration.
+            } else {
+                TURF_TRACE(ConcurrentMap_Grampa, 4, "[publishTableMigration] replacing flattree with single root", uptr(migration), 0);
+                // The entire previous flattree is being replaced.
+                Details::garbageCollectFlatTree((typename Details::FlatTree*) (oldRoot & ~ureg(1)));
+            }
+            // Caller will GC the TableMigration.
+        } else {
+            // We are either publishing a subtree of one or more tables, or replacing the entire map with multiple tables.
+            // In either case, there will be a flattree after this function returns.
+            TURF_ASSERT(migration->m_safeShift < sizeof(Hash) * 8);     // If m_numDestinations > 1, some index bits must remain after shifting
+            ureg oldRoot = m_root.load(turf::Consume);
+            if ((oldRoot & 1) == 0) {
+                // There's no flattree yet. This means the TableMigration is publishing the full range of hashes.
+                TURF_ASSERT(migration->m_baseHash == 0);
+                TURF_ASSERT((Hash(-1) >> migration->m_safeShift) == (migration->m_numDestinations - 1));
+                // The oldRoot should be the original source of the migration.
+                TURF_ASSERT((typename Details::Table*) oldRoot == migration->getSources()[0].table);
+                // Furthermore, it is guaranteed that there are no racing writes to m_root.
+                // Create a new flattree and store it to m_root.
+                TURF_TRACE(ConcurrentMap_Grampa, 5, "[publishTableMigration] replacing single root with flattree", uptr(migration), 0);
+                typename Details::FlatTree* flatTree = Details::FlatTree::create(migration->m_safeShift);
+                typename Details::Table* prevTable = NULL;
+                for (ureg i = 0; i < migration->m_numDestinations; i++) {
+                    typename Details::Table* newTable = migration->getDestinations()[i];
+                    flatTree->getTables()[i].storeNonatomic(newTable);
+                    if (newTable != prevTable) {
+                        newTable->isPublished.signal();
+                        prevTable = newTable;
+                    }
+                }
+                m_root.store(uptr(flatTree) | 1, turf::Release);  // Ensure visibility of flatTree->tables
+                // Caller will GC the TableMigration.
+                // Caller will also GC the old oldRoot since it's a source of the TableMigration.
+            } else {
+                // There is an existing flattree, and we are publishing one or more tables to it.
+                // Attempt to publish the subtree in a loop.
+                // The loop is necessary because we might get redirected in the middle of publishing.
+                TURF_TRACE(ConcurrentMap_Grampa, 6, "[publishTableMigration] publishing subtree to existing flattree", uptr(migration), 0);
+                typename Details::FlatTree* flatTree = (typename Details::FlatTree*) (oldRoot & ~ureg(1));
+                ureg subTreeEntriesPublished = 0;
+                typename Details::Table* tableToReplace = migration->getSources()[0].table;
+                // Wait here so that we only replace tables that are fully published.
+                // Otherwise, there will be a race between a subtree and its own children.
+                // (If all ManualResetEvent objects supported isPublished(), we could add a TURF_TRACE counter for this.
+                // In previous tests, such a counter does in fact get hit.)
+                tableToReplace->isPublished.wait();       
+                typename Details::Table* prevTable = NULL;
+                for (;;) {
+                publishLoop:
+                    if (migration->m_safeShift < flatTree->safeShift) {
+                        // We'll need to migrate to larger flattree before publishing our new subtree.
+                        // First, try to create a FlatTreeMigration with the necessary properties.
+                        // This will fail if an existing FlatTreeMigration has already been created using the same source.
+                        // In that case, we'll help complete the existing FlatTreeMigration, then we'll retry the loop.
+                        TURF_TRACE(ConcurrentMap_Grampa, 7, "[publishTableMigration] existing flattree too small", uptr(migration), 0);
+                        typename Details::FlatTreeMigration* flatTreeMigration = Details::createFlatTreeMigration(*this, flatTree, migration->m_safeShift);
+                        tableToReplace->jobCoordinator.runOne(flatTreeMigration);
+                        flatTreeMigration->m_completed.wait();      // flatTreeMigration->m_destination becomes entirely visible
+                        flatTree = flatTreeMigration->m_destination;
+                        // The FlatTreeMigration has already been GC'ed by the last worker.
+                        // Retry the loop.
+                    } else {
+                        ureg repeat = ureg(1) << (migration->m_safeShift - flatTree->safeShift);
+                        ureg dstStartIndex = migration->m_baseHash >> flatTree->safeShift;
+                        // The subtree we're about to publish fits inside the flattree.
+                        TURF_ASSERT(dstStartIndex + migration->m_numDestinations * repeat - 1 <= Hash(-1) >> flatTree->safeShift);
+                        // If a previous attempt to publish got redirected, resume publishing into the new flattree,
+                        // starting with the first subtree entry that has not yet been fully published, as given by subTreeEntriesPublished.
+                        // (Note: We could, in fact, restart the publish operation starting at entry 0. That would be valid too.
+                        // We are the only thread that can modify this particular range of the flattree at this time.)
+                        turf::Atomic<typename Details::Table*>* dstLeaf = flatTree->getTables() + dstStartIndex + (subTreeEntriesPublished * repeat);
+                        typename Details::Table** subFlatTree = migration->getDestinations();
+                        while (subTreeEntriesPublished < migration->m_numDestinations) {
+                            typename Details::Table* srcTable = subFlatTree[subTreeEntriesPublished];
+                            for (ureg r = repeat; r > 0; r--) {
+                                typename Details::Table* probeTable = tableToReplace;
+                                while (!dstLeaf->compareExchangeStrong(probeTable, srcTable, turf::Relaxed)) {
+                                    if (ureg(probeTable) == Details::RedirectFlatTree) {
+                                        // We've been redirected.
+                                        // Help with the FlatTreeMigration, then try again.
+                                        TURF_TRACE(ConcurrentMap_Grampa, 8, "[publishTableMigration] redirected", uptr(migration), uptr(dstLeaf));
+                                        typename Details::FlatTreeMigration* flatTreeMigration = Details::getExistingFlatTreeMigration(flatTree);
+                                        tableToReplace->jobCoordinator.runOne(flatTreeMigration);
+                                        flatTreeMigration->m_completed.wait();    // flatTreeMigration->m_destination becomes entirely visible
+                                        flatTree = flatTreeMigration->m_destination;
+                                        goto publishLoop;
+                                    }
+                                    // The only other possibility is that we were previously redirected, and the subtree entry got partially published.
+                                    TURF_TRACE(ConcurrentMap_Grampa, 9, "[publishTableMigration] recovering from partial publish", uptr(migration), 0);
+                                    TURF_ASSERT(probeTable == srcTable);
+                                }
+                                // The caller will GC the table) being replaced them since it's a source of the TableMigration.
+                                dstLeaf++;
+                            }
+                            if (prevTable != srcTable) {
+                                srcTable->isPublished.signal();
+                                prevTable = srcTable;
+                            }
+                            subTreeEntriesPublished++;
+                        }
+                        // We've successfully published the migrated sub-flattree.
+                        // Caller will GC the TableMigration.
+                        break;
+                    }
+                }
+            }
+        }
+    }
+
+    void publishFlatTreeMigration(typename Details::FlatTreeMigration* migration) {
+        // There are no racing writes.
+        // Old root must be the migration source (a flattree).
+        TURF_ASSERT(m_root.loadNonatomic() == (ureg(migration->m_source) | 1));
+        // Publish the new flattree, making entire table contents visible.
+        m_root.store(uptr(migration->m_destination) | 1, turf::Release);
+        // Don't GC the old flattree. The FlatTreeMigration will do that, since it's a source.
+    }
+
+    // A Mutator represents a known cell in the hash table.
+    // It's meant for manipulations within a temporary function scope.
+    // Obviously you must not call QSBR::Update while holding a Mutator.
+    // Any operation that modifies the table (exchangeValue, eraseValue)
+    // may be forced to follow a redirected cell, which changes the Mutator itself.
+    // Note that even if the Mutator was constructed from an existing cell,
+    // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
+    // or if another thread deletes the key between the two steps.
+    class Mutator {
+    private:
+        friend class ConcurrentMap_Grampa;
+
+        ConcurrentMap_Grampa& m_map;
+        typename Details::Table* m_table;
+        ureg m_sizeMask;
+        typename Details::Cell* m_cell;
+        Value m_value;
+
+        // Constructor: Find existing cell
+        Mutator(ConcurrentMap_Grampa& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_Grampa, 10, "[Mutator] find constructor called", uptr(map.m_root.load(turf::Relaxed)), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                if (!m_map.locateTable(m_table, m_sizeMask, hash))
+                    return;
+                m_cell = Details::find(hash, m_table, m_sizeMask);
+                if (!m_cell)
+                    return;
+                m_value = m_cell->value.load(turf::Consume);
+                if (m_value != Value(ValueTraits::Redirect))
+                    return;                        // Found an existing value
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_Grampa, 11, "[Mutator] find was redirected", uptr(m_table), 0);
+                m_table->jobCoordinator.participate();
+                // Try again using the latest root.
+            }
+        }
+
+        // Constructor: Insert cell
+        Mutator(ConcurrentMap_Grampa& map, Key key) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_Grampa, 12, "[Mutator] insert constructor called", uptr(map.m_root.load(turf::Relaxed)), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                if (!m_map.locateTable(m_table, m_sizeMask, hash)) {
+                    m_map.createInitialTable(Details::MinTableSize);
+                } else {
+                    ureg overflowIdx;
+                    switch (Details::insert(hash, m_table, m_sizeMask, m_cell, overflowIdx)) {   // Modifies m_cell
+                        case Details::InsertResult_InsertedNew: {
+                            // We've inserted a new cell. Don't load m_cell->value.
+                            return;     
+                        }
+                        case Details::InsertResult_AlreadyFound: {
+                            // The hash was already found in the table.
+                            m_value = m_cell->value.load(turf::Consume);
+                            if (m_value == Value(ValueTraits::Redirect)) {
+                                // We've encountered a Redirect value.
+                                TURF_TRACE(ConcurrentMap_Grampa, 13, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
+                                break;   // Help finish the migration.
+                            }
+                            return;     // Found an existing value
+                        }
+                        case Details::InsertResult_Overflow: {
+                            Details::beginTableMigration(m_map, m_table, overflowIdx);
+                            break;
+                        }
+                    }
+                    // A migration has been started (either by us, or another thread). Participate until it's complete.
+                    m_table->jobCoordinator.participate();
+                }
+                // Try again using the latest root.
+            }
+        }
+
+    public:
+        Value getValue() const {
+            // Return previously loaded value. Don't load it again.
+            return m_value;
+        }
+
+        Value exchangeValue(Value desired) {
+            TURF_ASSERT(desired != Value(ValueTraits::NullValue));
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_Grampa, 14, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
+            for (;;) {
+                Value oldValue = m_value;
+                if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
+                    // Exchange was successful. Return previous value.
+                    TURF_TRACE(ConcurrentMap_Grampa, 15, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
+                    Value result = m_value;
+                    m_value = desired;  // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    TURF_TRACE(ConcurrentMap_Grampa, 16, "[Mutator::exchangeValue] detected race to write value", uptr(m_table), uptr(m_value));
+                    if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
+                        TURF_TRACE(ConcurrentMap_Grampa, 17, "[Mutator::exchangeValue] racing write inserted new value", uptr(m_table), uptr(m_value));
+                    }
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we exchanged with ourselves, and just let the racing write win.
+                    return desired;
+                }
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_Grampa, 18, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
+                Hash hash = m_cell->hash.load(turf::Relaxed);
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the latest table.
+                    // FIXME: locateTable() could return false if the map is concurrently cleared (m_root set to 0).
+                    // This is not concern yet since clear() is not implemented.
+                    bool exists = m_map.locateTable(m_table, m_sizeMask, hash);
+                    TURF_ASSERT(exists);
+                    TURF_UNUSED(exists);
+                    m_value = Value(ValueTraits::NullValue);
+                    ureg overflowIdx;
+                    switch (Details::insert(hash, m_table, m_sizeMask, m_cell, overflowIdx)) {   // Modifies m_cell
+                    case Details::InsertResult_AlreadyFound:
+                        m_value = m_cell->value.load(turf::Consume);
+                        if (m_value == Value(ValueTraits::Redirect)) {
+                            TURF_TRACE(ConcurrentMap_Grampa, 19, "[Mutator::exchangeValue] was re-redirected", uptr(m_table), uptr(m_value));
+                            break;
+                        }
+                        goto breakOuter;
+                    case Details::InsertResult_InsertedNew:
+                        goto breakOuter;
+                    case Details::InsertResult_Overflow:
+                        TURF_TRACE(ConcurrentMap_Grampa, 20, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), overflowIdx);
+                        Details::beginTableMigration(m_map, m_table, overflowIdx);
+                        break;
+                    }
+                    // We were redirected... again
+                }
+            breakOuter:
+                ;
+                // Try again in the new table.
+            }
+        }
+
+        void setValue(Value desired) {
+            exchangeValue(desired);
+        }
+
+        Value eraseValue() {
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_Grampa, 21, "[Mutator::eraseValue] called", uptr(m_table), uptr(m_value));
+            for (;;) {
+                if (m_value == Value(ValueTraits::NullValue))
+                    return m_value;
+                TURF_ASSERT(m_cell);    // m_value is non-NullValue, therefore cell must have been found or inserted.
+                if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
+                    // Exchange was successful and a non-NullValue value was erased and returned by reference in m_value.
+                    TURF_ASSERT(m_value != Value(ValueTraits::NullValue));   // Implied by the test at the start of the loop.
+                    Value result = m_value;
+                    m_value = Value(ValueTraits::NullValue);   // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                TURF_TRACE(ConcurrentMap_Grampa, 22, "[Mutator::eraseValue] detected race to write value", uptr(m_table), uptr(m_value));
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we erased nothing, and just let the racing write win.
+                    return Value(ValueTraits::NullValue);
+                }
+                // We've been redirected to a new table.
+                TURF_TRACE(ConcurrentMap_Grampa, 23, "[Mutator::eraseValue] was redirected", uptr(m_table), uptr(m_cell));
+                Hash hash = m_cell->hash.load(turf::Relaxed);           // Re-fetch hash
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the latest table.
+                    if (!m_map.locateTable(m_table, m_sizeMask, hash))
+                        m_cell = NULL;
+                    else
+                        m_cell = Details::find(hash, m_table, m_sizeMask);
+                    if (!m_cell) {
+                        m_value = Value(ValueTraits::NullValue);
+                        return m_value;
+                    }
+                    m_value = m_cell->value.load(turf::Relaxed);
+                    if (m_value != Value(ValueTraits::Redirect))
+                        break;
+                    TURF_TRACE(ConcurrentMap_Grampa, 24, "[Mutator::eraseValue] was re-redirected", uptr(m_table), uptr(m_cell));
+                }
+            }
+        }
+    };
+
+    Mutator insert(Key key) {
+        return Mutator(*this, key);
+    }
+
+    Mutator find(Key key) {
+        return Mutator(*this, key, false);
+    }
+
+    // Lookup without creating a temporary Mutator.
+    Value get(Key key) {
+        Hash hash = KeyTraits::hash(key);
+        TURF_TRACE(ConcurrentMap_Grampa, 25, "[get] called", uptr(this), uptr(hash));
+        for (;;) {
+            typename Details::Table* table;
+            ureg sizeMask;
+            if (!locateTable(table, sizeMask, hash))
+                return Value(ValueTraits::NullValue);
+            typename Details::Cell* cell = Details::find(hash, table, sizeMask);
+            if (!cell)
+                return Value(ValueTraits::NullValue);
+            Value value = cell->value.load(turf::Consume);
+            if (value != Value(ValueTraits::Redirect))
+                return value;                        // Found an existing value
+            // We've been redirected to a new table. Help with the migration.
+            TURF_TRACE(ConcurrentMap_Grampa, 26, "[get] was redirected", uptr(table), 0);
+            table->jobCoordinator.participate();
+            // Try again in the new table.
+        }
+    }
+
+    Value insert(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value exchange(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value erase(Key key) {
+        Mutator iter(*this, key, false);
+        return iter.eraseValue();
+    }
+
+    // The easiest way to implement an Iterator is to prevent all Redirects.
+    // The currrent Iterator does that by forbidding concurrent inserts.
+    // To make it work with concurrent inserts, we'd need a way to block TableMigrations as the Iterator visits each table.
+    // FlatTreeMigrations, too.
+    class Iterator {
+    private:
+        typename Details::FlatTree* m_flatTree;
+        ureg m_flatTreeIdx;
+        typename Details::Table* m_table;
+        ureg m_idx;
+        Key m_hash;
+        Value m_value;
+
+    public:
+        Iterator(ConcurrentMap_Grampa& map) {
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            ureg root = map.m_root.load(turf::Consume);
+            if (root & 1) {
+                m_flatTree = (typename Details::FlatTree*) (root & ~ureg(1));
+                TURF_ASSERT(m_flatTree->getSize() > 0);
+                m_flatTreeIdx = 0;
+                m_table = m_flatTree->getTables()[0].load(turf::Consume);
+                TURF_ASSERT(m_table);
+                m_idx = -1;
+            } else {
+                m_flatTree = NULL;
+                m_flatTreeIdx = 0;
+                m_table = (typename Details::Table*) root;
+                m_idx = -1;
+            }
+            if (m_table) {
+                next();
+            } else {
+                m_hash = KeyTraits::NullHash;
+                m_value = Value(ValueTraits::NullValue);
+            }
+        }
+
+        void next() {
+            TURF_ASSERT(m_table);
+            TURF_ASSERT(isValid() || m_idx == -1);  // Either the Iterator is already valid, or we've just started iterating.
+            for (;;) {
+            searchInTable:
+                m_idx++;
+                if (m_idx <= m_table->sizeMask) {
+                    // Index still inside range of table.
+                    typename Details::CellGroup* group = m_table->getCellGroups() + (m_idx >> 2);
+                    typename Details::Cell *cell = group->cells + (m_idx & 3);
+                    m_hash = cell->hash.load(turf::Relaxed);
+                    if (m_hash != KeyTraits::NullHash) {
+                        // Cell has been reserved.
+                        m_value = cell->value.load(turf::Relaxed);
+                        TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
+                        if (m_value != Value(ValueTraits::NullValue))
+                            return;     // Yield this cell.
+                    }
+                } else {
+                    // We've advanced past the end of this table.
+                    if (m_flatTree) {
+                        // Scan for the next unique table in the flattree.
+                        while (++m_flatTreeIdx < m_flatTree->getSize()) {
+                            typename Details::Table* nextTable = m_flatTree->getTables()[m_flatTreeIdx].load(turf::Consume);
+                            if (nextTable != m_table) {
+                                // Found the next table.
+                                m_table = nextTable;
+                                m_idx = -1;
+                                goto searchInTable;       // Continue iterating in this table.
+                            }
+                        }
+                    }
+                    // That's the end of the entire map.
+                    m_hash = KeyTraits::NullHash;
+                    m_value = Value(ValueTraits::NullValue);
+                    return;
+                }
+            }
+        }
+
+        bool isValid() const {
+            return m_value != Value(ValueTraits::NullValue);
+        }
+
+        Key getKey() const {
+            TURF_ASSERT(isValid());
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            return KeyTraits::dehash(m_hash);
+        }
+
+        Value getValue() const {
+            TURF_ASSERT(isValid());
+            return m_value;
+        }
+    };
+};
+
+} // namespace junction
+
+#endif // JUNCTION_CONCURRENTMAP_GRAMPA_H
diff --git a/junction/ConcurrentMap_LeapFrog.cpp b/junction/ConcurrentMap_LeapFrog.cpp
new file mode 100644 (file)
index 0000000..4f1a539
--- /dev/null
@@ -0,0 +1,37 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/ConcurrentMap_LeapFrog.h>
+
+namespace junction {
+    
+TURF_TRACE_DEFINE_BEGIN(ConcurrentMap_LeapFrog, 17) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[Mutator] find constructor called")
+TURF_TRACE_DEFINE("[Mutator] find was redirected")
+TURF_TRACE_DEFINE("[Mutator] insert constructor called")
+TURF_TRACE_DEFINE("[Mutator] insert was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] called")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] exchanged Value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] racing write inserted new value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was re-redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] overflow after redirect")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] called")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was re-redirected")
+TURF_TRACE_DEFINE("[get] called")
+TURF_TRACE_DEFINE("[get] was redirected")
+TURF_TRACE_DEFINE_END(ConcurrentMap_LeapFrog, 17)
+
+} // namespace junction
diff --git a/junction/ConcurrentMap_LeapFrog.h b/junction/ConcurrentMap_LeapFrog.h
new file mode 100644 (file)
index 0000000..3cefc6f
--- /dev/null
@@ -0,0 +1,336 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_CONCURRENTMAP_LEAPFROG_H
+#define JUNCTION_CONCURRENTMAP_LEAPFROG_H
+
+#include <junction/Core.h>
+#include <junction/details/LeapFrog.h>
+#include <junction/QSBR.h>
+#include <turf/Heap.h>
+#include <turf/Trace.h>
+
+namespace junction {
+
+TURF_TRACE_DECLARE(ConcurrentMap_LeapFrog, 17)
+
+template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V>>
+class ConcurrentMap_LeapFrog {
+public:
+    typedef K Key;
+    typedef V Value;
+    typedef KT KeyTraits;
+    typedef VT ValueTraits;
+    typedef typename turf::util::BestFit<Key>::Unsigned Hash;
+    typedef details::LeapFrog<ConcurrentMap_LeapFrog> Details;
+
+private:
+    turf::Atomic<typename Details::Table*> m_root;
+
+public:
+    ConcurrentMap_LeapFrog(ureg capacity) : m_root(Details::Table::create(capacity)) {
+    }
+
+    ~ConcurrentMap_LeapFrog() {
+        typename Details::Table* table = m_root.loadNonatomic();
+        table->destroy();
+    }
+
+    // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
+    // after all the threads participating in the migration have completed their work.
+    void publishTableMigration(typename Details::TableMigration* migration) {
+        // There are no racing calls to this function.
+        typename Details::Table* oldRoot = m_root.loadNonatomic();
+        m_root.store(migration->m_destination, turf::Release);
+        TURF_ASSERT(oldRoot == migration->getSources()[0].table);
+        // Caller will GC the TableMigration and the source table.
+    }
+
+    // A Mutator represents a known cell in the hash table.
+    // It's meant for manipulations within a temporary function scope.
+    // Obviously you must not call QSBR::Update while holding a Mutator.
+    // Any operation that modifies the table (exchangeValue, eraseValue)
+    // may be forced to follow a redirected cell, which changes the Mutator itself.
+    // Note that even if the Mutator was constructed from an existing cell,
+    // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
+    // or if another thread deletes the key between the two steps.
+    class Mutator {
+    private:
+        friend class ConcurrentMap_LeapFrog;
+
+        ConcurrentMap_LeapFrog& m_map;
+        typename Details::Table* m_table;
+        typename Details::Cell* m_cell;
+        Value m_value;
+
+        // Constructor: Find existing cell
+        Mutator(ConcurrentMap_LeapFrog& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_LeapFrog, 0, "[Mutator] find constructor called", uptr(m_table), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                m_table = m_map.m_root.load(turf::Consume);
+                m_cell = Details::find(hash, m_table);
+                if (!m_cell)
+                    return;
+                m_value = m_cell->value.load(turf::Consume);
+                if (m_value != Value(ValueTraits::Redirect))
+                    return;                        // Found an existing value
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_LeapFrog, 1, "[Mutator] find was redirected", uptr(m_table), 0);
+                m_table->jobCoordinator.participate();
+                // Try again using the latest root.
+            }
+        }
+
+        // Constructor: Insert cell
+        Mutator(ConcurrentMap_LeapFrog& map, Key key) : m_map(map), m_table(map.m_root.load(turf::Consume)), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_LeapFrog, 2, "[Mutator] insert constructor called", uptr(m_table), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                m_table = m_map.m_root.load(turf::Consume);
+                ureg overflowIdx;
+                switch (Details::insert(hash, m_table, m_cell, overflowIdx)) {   // Modifies m_cell
+                    case Details::InsertResult_InsertedNew: {
+                        // We've inserted a new cell. Don't load m_cell->value.
+                        return;     
+                    }
+                    case Details::InsertResult_AlreadyFound: {
+                        // The hash was already found in the table.
+                        m_value = m_cell->value.load(turf::Consume);
+                        if (m_value == Value(ValueTraits::Redirect)) {
+                            // We've encountered a Redirect value.
+                            TURF_TRACE(ConcurrentMap_LeapFrog, 3, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
+                            break;   // Help finish the migration.
+                        }
+                        return;     // Found an existing value
+                    }
+                    case Details::InsertResult_Overflow: {
+                        Details::beginTableMigration(m_map, m_table, overflowIdx);
+                        break;
+                    }
+                }
+                // A migration has been started (either by us, or another thread). Participate until it's complete.
+                m_table->jobCoordinator.participate();
+                // Try again using the latest root.
+            }
+        }
+
+    public:
+        Value getValue() const {
+            // Return previously loaded value. Don't load it again.
+            return Value(m_value);
+        }
+
+        Value exchangeValue(Value desired) {
+            TURF_ASSERT(desired != Value(ValueTraits::NullValue));
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_LeapFrog, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
+            for (;;) {
+                Value oldValue = m_value;
+                if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
+                    // Exchange was successful. Return previous value.
+                    TURF_TRACE(ConcurrentMap_LeapFrog, 5, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
+                    Value result = m_value;
+                    m_value = desired;  // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    TURF_TRACE(ConcurrentMap_LeapFrog, 6, "[Mutator::exchangeValue] detected race to write value", uptr(m_table), uptr(m_value));
+                    if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
+                        TURF_TRACE(ConcurrentMap_LeapFrog, 7, "[Mutator::exchangeValue] racing write inserted new value", uptr(m_table), uptr(m_value));
+                    }
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we exchanged with ourselves, and just let the racing write win.
+                    return desired;
+                }
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_LeapFrog, 8, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
+                Hash hash = m_cell->hash.load(turf::Relaxed);
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the new table.
+                    m_table = m_map.m_root.load(turf::Consume);
+                    m_value = Value(ValueTraits::NullValue);
+                    ureg overflowIdx;
+                    switch (Details::insert(hash, m_table, m_cell, overflowIdx)) {   // Modifies m_cell
+                    case Details::InsertResult_AlreadyFound:
+                        m_value = m_cell->value.load(turf::Consume);
+                        if (m_value == Value(ValueTraits::Redirect)) {
+                            TURF_TRACE(ConcurrentMap_LeapFrog, 9, "[Mutator::exchangeValue] was re-redirected", uptr(m_table), uptr(m_value));
+                            break;
+                        }
+                        goto breakOuter;
+                    case Details::InsertResult_InsertedNew:
+                        goto breakOuter;
+                    case Details::InsertResult_Overflow:
+                        TURF_TRACE(ConcurrentMap_LeapFrog, 10, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), overflowIdx);
+                        Details::beginTableMigration(m_map, m_table, overflowIdx);
+                        break;
+                    }
+                    // We were redirected... again
+                }
+            breakOuter:
+                ;
+                // Try again in the new table.
+            }
+        }
+
+        void setValue(Value desired) {
+            exchangeValue(desired);
+        }
+
+        Value eraseValue() {
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_LeapFrog, 11, "[Mutator::eraseValue] called", uptr(m_table), uptr(m_cell));
+            for (;;) {
+                if (m_value == Value(ValueTraits::NullValue))
+                    return Value(m_value);
+                TURF_ASSERT(m_cell);    // m_value is non-NullValue, therefore cell must have been found or inserted.
+                if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
+                    // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
+                    TURF_ASSERT(m_value != ValueTraits::NullValue);   // Implied by the test at the start of the loop.
+                    Value result = m_value;
+                    m_value = Value(ValueTraits::NullValue);   // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                TURF_TRACE(ConcurrentMap_LeapFrog, 12, "[Mutator::eraseValue] detected race to write value", uptr(m_table), uptr(m_cell));
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we erased nothing, and just let the racing write win.
+                    return Value(ValueTraits::NullValue);
+                }
+                // We've been redirected to a new table.
+                TURF_TRACE(ConcurrentMap_LeapFrog, 13, "[Mutator::eraseValue] was redirected", uptr(m_table), uptr(m_cell));
+                Hash hash = m_cell->hash.load(turf::Relaxed);           // Re-fetch hash
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the new table.
+                    m_table = m_map.m_root.load(turf::Consume);
+                    m_cell = Details::find(hash, m_table);
+                    if (!m_cell) {
+                        m_value = Value(ValueTraits::NullValue);
+                        return m_value;
+                    }
+                    m_value = m_cell->value.load(turf::Relaxed);
+                    if (m_value != Value(ValueTraits::Redirect))
+                        break;
+                    TURF_TRACE(ConcurrentMap_LeapFrog, 14, "[Mutator::eraseValue] was re-redirected", uptr(m_table), uptr(m_cell));
+                }
+            }
+        }
+    };
+
+    Mutator insert(Key key) {
+        return Mutator(*this, key);
+    }
+
+    Mutator find(Key key) {
+        return Mutator(*this, key, false);
+    }
+
+    // Lookup without creating a temporary Mutator.
+    Value get(Key key) {
+        Hash hash = KeyTraits::hash(key);
+        TURF_TRACE(ConcurrentMap_LeapFrog, 15, "[get] called", uptr(hash), 0);
+        for (;;) {
+            typename Details::Table* table = m_root.load(turf::Consume);
+            typename Details::Cell* cell = Details::find(hash, table);
+            if (!cell)
+                return Value(ValueTraits::NullValue);
+            Value value = cell->value.load(turf::Consume);
+            if (value != Value(ValueTraits::Redirect))
+                return value;                        // Found an existing value
+            // We've been redirected to a new table. Help with the migration.
+            TURF_TRACE(ConcurrentMap_LeapFrog, 16, "[get] was redirected", uptr(table), uptr(hash));
+            table->jobCoordinator.participate();
+            // Try again in the new table.
+        }
+    }
+
+    Value insert(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value exchange(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value erase(Key key) {
+        Mutator iter(*this, key, false);
+        return iter.eraseValue();
+    }
+
+    // The easiest way to implement an Iterator is to prevent all Redirects.
+    // The currrent Iterator does that by forbidding concurrent inserts.
+    // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
+    class Iterator {
+    private:
+        typename Details::Table* m_table;
+        ureg m_idx;
+        Key m_hash;
+        Value m_value;
+
+    public:
+        Iterator(ConcurrentMap_LeapFrog& map) {
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            m_table = map.m_root.load(turf::Consume);
+            m_idx = -1;
+            next();
+        }
+
+        void next() {
+            TURF_ASSERT(m_table);
+            TURF_ASSERT(isValid() || m_idx == -1);  // Either the Iterator is already valid, or we've just started iterating.
+            while (++m_idx <= m_table->sizeMask) {
+                // Index still inside range of table.
+                typename Details::CellGroup* group = m_table->getCellGroups() + (m_idx >> 2);
+                typename Details::Cell *cell = group->cells + (m_idx & 3);
+                m_hash = cell->hash.load(turf::Relaxed);
+                if (m_hash != KeyTraits::NullHash) {
+                    // Cell has been reserved.
+                    m_value = cell->value.load(turf::Relaxed);
+                    TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
+                    if (m_value != Value(ValueTraits::NullValue))
+                        return;     // Yield this cell.
+                }
+            }
+            // That's the end of the map.
+            m_hash = KeyTraits::NullHash;
+            m_value = ValueTraits::NullValue;
+        }
+
+        bool isValid() const {
+            return m_value != Value(ValueTraits::NullValue);
+        }
+
+        Key getKey() const {
+            TURF_ASSERT(isValid());
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            return KeyTraits::dehash(m_hash);
+        }
+
+        Value getValue() const {
+            TURF_ASSERT(isValid());
+            return m_value;
+        }
+    };
+};
+
+} // namespace junction
+
+#endif // JUNCTION_CONCURRENTMAP_LEAPFROG_H
diff --git a/junction/ConcurrentMap_Linear.cpp b/junction/ConcurrentMap_Linear.cpp
new file mode 100644 (file)
index 0000000..f351594
--- /dev/null
@@ -0,0 +1,38 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/ConcurrentMap_Linear.h>
+
+namespace junction {
+    
+TURF_TRACE_DEFINE_BEGIN(ConcurrentMap_Linear, 18) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[Mutator] find constructor called")
+TURF_TRACE_DEFINE("[Mutator] find was redirected")
+TURF_TRACE_DEFINE("[Mutator] insert constructor called")
+TURF_TRACE_DEFINE("[Mutator] insert was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] called")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] ran out of valuesRemaining")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] exchanged Value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] racing write inserted new value")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] was re-redirected")
+TURF_TRACE_DEFINE("[Mutator::exchangeValue] overflow after redirect")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] called")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] detected race to write value")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was redirected")
+TURF_TRACE_DEFINE("[Mutator::eraseValue] was re-redirected")
+TURF_TRACE_DEFINE("[get] called")
+TURF_TRACE_DEFINE("[get] was redirected")
+TURF_TRACE_DEFINE_END(ConcurrentMap_Linear, 18)
+
+} // namespace junction
diff --git a/junction/ConcurrentMap_Linear.h b/junction/ConcurrentMap_Linear.h
new file mode 100644 (file)
index 0000000..1de64b2
--- /dev/null
@@ -0,0 +1,358 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_CONCURRENTMAP_LINEAR_H
+#define JUNCTION_CONCURRENTMAP_LINEAR_H
+
+#include <junction/Core.h>
+#include <junction/details/Linear.h>
+#include <junction/QSBR.h>
+#include <turf/Heap.h>
+#include <turf/Trace.h>
+
+namespace junction {
+
+TURF_TRACE_DECLARE(ConcurrentMap_Linear, 18)
+
+template <typename K, typename V, class KT = DefaultKeyTraits<K>, class VT = DefaultValueTraits<V>>
+class ConcurrentMap_Linear {
+public:
+    typedef K Key;
+    typedef V Value;
+    typedef KT KeyTraits;
+    typedef VT ValueTraits;
+    typedef typename turf::util::BestFit<Key>::Unsigned Hash;
+    typedef details::Linear<ConcurrentMap_Linear> Details;
+
+private:
+    turf::Atomic<typename Details::Table*> m_root;
+
+public:
+    ConcurrentMap_Linear(ureg capacity) {
+        ureg limitNumValues = capacity * 3 / 4;
+        m_root.storeNonatomic(Details::Table::create(capacity, limitNumValues));
+    }
+
+    ~ConcurrentMap_Linear() {
+        typename Details::Table* table = m_root.loadNonatomic();
+        table->destroy();
+    }
+
+    // publishTableMigration() is called by exactly one thread from Details::TableMigration::run()
+    // after all the threads participating in the migration have completed their work.
+    void publishTableMigration(typename Details::TableMigration* migration) {
+        // There are no racing calls to this function.
+        typename Details::Table* oldRoot = m_root.loadNonatomic();
+        m_root.store(migration->m_destination, turf::Release);
+        TURF_ASSERT(oldRoot == migration->m_source);
+        // Caller will GC the TableMigration and the source table.
+    }
+
+    // A Mutator represents a known cell in the hash table.
+    // It's meant for manipulations within a temporary function scope.
+    // Obviously you must not call QSBR::Update while holding a Mutator.
+    // Any operation that modifies the table (exchangeValue, eraseValue)
+    // may be forced to follow a redirected cell, which changes the Mutator itself.
+    // Note that even if the Mutator was constructed from an existing cell,
+    // exchangeValue() can still trigger a resize if the existing cell was previously marked deleted,
+    // or if another thread deletes the key between the two steps.
+    class Mutator {
+    private:
+        friend class ConcurrentMap_Linear;
+
+        ConcurrentMap_Linear& m_map;
+        typename Details::Table* m_table;
+        typename Details::Cell* m_cell;
+        Value m_value;
+
+        // Constructor: Find existing cell
+        Mutator(ConcurrentMap_Linear& map, Key key, bool) : m_map(map), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_Linear, 0, "[Mutator] find constructor called", uptr(m_table), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                m_table = m_map.m_root.load(turf::Consume);
+                m_cell = Details::find(hash, m_table);
+                if (!m_cell)
+                    return;
+                m_value = m_cell->value.load(turf::Consume);
+                if (m_value != Value(ValueTraits::Redirect))
+                    return;                        // Found an existing value
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_Linear, 1, "[Mutator] find was redirected", uptr(m_table), uptr(0));
+                m_table->jobCoordinator.participate();
+                // Try again using the latest root.
+            }
+        }
+
+        // Constructor: Insert cell
+        Mutator(ConcurrentMap_Linear& map, Key key) : m_map(map), m_table(map.m_root.load(turf::Consume)), m_value(Value(ValueTraits::NullValue)) {
+            TURF_TRACE(ConcurrentMap_Linear, 2, "[Mutator] insert constructor called", uptr(m_table), uptr(key));
+            Hash hash = KeyTraits::hash(key);
+            for (;;) {
+                m_table = m_map.m_root.load(turf::Consume);
+                switch (Details::insert(hash, m_table, m_cell)) {   // Modifies m_cell
+                    case Details::InsertResult_InsertedNew: {
+                        // We've inserted a new cell. Don't load m_cell->value.
+                        return;     
+                    }
+                    case Details::InsertResult_AlreadyFound: {
+                        // The hash was already found in the table.
+                        m_value = m_cell->value.load(turf::Consume);
+                        if (m_value == Value(ValueTraits::Redirect)) {
+                            // We've encountered a Redirect value.
+                            TURF_TRACE(ConcurrentMap_Linear, 3, "[Mutator] insert was redirected", uptr(m_table), uptr(m_value));
+                            break;   // Help finish the migration.
+                        }
+                        return;     // Found an existing value
+                    }
+                    case Details::InsertResult_Overflow: {
+                        Details::beginTableMigration(m_map, m_table);
+                        break;
+                    }
+                }
+                // A migration has been started (either by us, or another thread). Participate until it's complete.
+                m_table->jobCoordinator.participate();
+                // Try again using the latest root.
+            }
+        }
+
+    public:
+        Value getValue() const {
+            // Return previously loaded value. Don't load it again.
+            return Value(m_value);
+        }
+
+        Value exchangeValue(Value desired) {
+            TURF_ASSERT(desired != Value(ValueTraits::NullValue));
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_Linear, 4, "[Mutator::exchangeValue] called", uptr(m_table), uptr(m_value));
+            for (;;) {
+                Value oldValue = m_value;
+                s32 prevRemainingValues = s32(-1);
+                if (oldValue == Value(ValueTraits::NullValue)) {
+                    // It's a deleted or newly initialized cell.
+                    // Decrement remainingValues to ensure we have permission to (re)insert a value.
+                    prevRemainingValues = m_table->valuesRemaining.fetchSub(1, turf::Relaxed);
+                    if (prevRemainingValues <= 0) {
+                        TURF_TRACE(ConcurrentMap_Linear, 5, "[Mutator::exchangeValue] ran out of valuesRemaining", uptr(m_table), prevRemainingValues);
+                        // Can't (re)insert any more values.
+                        // There are two ways this can happen. One with a TableMigration already in progress, and one without:
+                        // 1. A TableMigration puts a cap on the number of values late-arriving threads are allowed to insert.
+                        // 2. Two threads race to insert the same key, and it's the last free cell in the table.
+                        // (Note: We could get tid of the valuesRemaining counter by handling the possibility of migration failure,
+                        // as LeapFrog and Grampa do...)
+                        m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);    // Undo valuesRemaining decrement
+                        // Since we don't know whether there's already a TableMigration in progress, always attempt to start one here:
+                        Details::beginTableMigration(m_map, m_table);
+                        goto helpMigrate;
+                    }
+                }
+                if (m_cell->value.compareExchangeStrong(m_value, desired, turf::ConsumeRelease)) {
+                    // Exchange was successful. Return previous value.
+                    TURF_TRACE(ConcurrentMap_Linear, 6, "[Mutator::exchangeValue] exchanged Value", uptr(m_value), uptr(desired));
+                    Value result = m_value;
+                    m_value = desired;  // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    TURF_TRACE(ConcurrentMap_Linear, 7, "[Mutator::exchangeValue] detected race to write value", uptr(m_table), uptr(m_value));
+                    if (oldValue == Value(ValueTraits::NullValue) && m_value != Value(ValueTraits::NullValue)) {
+                        TURF_TRACE(ConcurrentMap_Linear, 8, "[Mutator::exchangeValue] racing write inserted new value", uptr(m_table), uptr(m_value));
+                        m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);    // Undo valuesRemaining decrement
+                    }
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we exchanged with ourselves, and just let the racing write win.
+                    return desired;
+                }
+                // We've encountered a Redirect value. Help finish the migration.
+                TURF_TRACE(ConcurrentMap_Linear, 9, "[Mutator::exchangeValue] was redirected", uptr(m_table), uptr(m_value));
+            helpMigrate:
+                // Help migrate to new table.
+                Hash hash = m_cell->hash.load(turf::Relaxed);
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the new table.
+                    m_table = m_map.m_root.load(turf::Consume);
+                    m_value = Value(ValueTraits::NullValue);
+                    switch (Details::insert(hash, m_table, m_cell)) {   // Modifies m_cell
+                    case Details::InsertResult_AlreadyFound:
+                        m_value = m_cell->value.load(turf::Consume);
+                        if (m_value == Value(ValueTraits::Redirect)) {
+                            TURF_TRACE(ConcurrentMap_Linear, 10, "[Mutator::exchangeValue] was re-redirected", uptr(m_table), uptr(m_value));
+                            break;
+                        }
+                        goto breakOuter;
+                    case Details::InsertResult_InsertedNew:
+                        goto breakOuter;
+                    case Details::InsertResult_Overflow:
+                        TURF_TRACE(ConcurrentMap_Linear, 11, "[Mutator::exchangeValue] overflow after redirect", uptr(m_table), 0);
+                        Details::beginTableMigration(m_map, m_table);
+                        break;
+                    }
+                    // We were redirected... again
+                }
+            breakOuter:
+                ;
+                // Try again in the new table.
+            }
+        }
+
+        void setValue(Value desired) {
+            exchangeValue(desired);
+        }
+
+        Value eraseValue() {
+            TURF_ASSERT(m_cell);    // Cell must have been found or inserted
+            TURF_TRACE(ConcurrentMap_Linear, 12, "[Mutator::eraseValue] called", uptr(m_table), m_cell - m_table->getCells());
+            for (;;) {
+                if (m_value == Value(ValueTraits::NullValue))
+                    return Value(m_value);
+                TURF_ASSERT(m_cell);    // m_value is non-NullValue, therefore cell must have been found or inserted.
+                if (m_cell->value.compareExchangeStrong(m_value, Value(ValueTraits::NullValue), turf::Consume)) {
+                    // Exchange was successful and a non-NULL value was erased and returned by reference in m_value.
+                    TURF_ASSERT(m_value != ValueTraits::NullValue);   // Implied by the test at the start of the loop.
+                    m_table->valuesRemaining.fetchAdd(1, turf::Relaxed);
+                    Value result = m_value;
+                    m_value = Value(ValueTraits::NullValue);   // Leave the mutator in a valid state
+                    return result;
+                }
+                // The CAS failed and m_value has been updated with the latest value.
+                TURF_TRACE(ConcurrentMap_Linear, 13, "[Mutator::eraseValue] detected race to write value", uptr(m_table), m_cell - m_table->getCells());
+                if (m_value != Value(ValueTraits::Redirect)) {
+                    // There was a racing write (or erase) to this cell.
+                    // Pretend we erased nothing, and just let the racing write win.
+                    return Value(ValueTraits::NullValue);
+                }
+                // We've been redirected to a new table.
+                TURF_TRACE(ConcurrentMap_Linear, 14, "[Mutator::eraseValue] was redirected", uptr(m_table), m_cell - m_table->getCells());
+                Hash hash = m_cell->hash.load(turf::Relaxed);           // Re-fetch hash
+                for (;;) {
+                    // Help complete the migration.
+                    m_table->jobCoordinator.participate();
+                    // Try again in the new table.
+                    m_table = m_map.m_root.load(turf::Consume);
+                    m_cell = Details::find(hash, m_table);
+                    if (!m_cell) {
+                        m_value = Value(ValueTraits::NullValue);
+                        return m_value;
+                    }
+                    m_value = m_cell->value.load(turf::Relaxed);
+                    if (m_value != Value(ValueTraits::Redirect))
+                        break;
+                    TURF_TRACE(ConcurrentMap_Linear, 15, "[Mutator::eraseValue] was re-redirected", uptr(m_table), m_cell - m_table->getCells());
+                }
+            }
+        }
+    };
+
+    Mutator insert(Key key) {
+        return Mutator(*this, key);
+    }
+
+    Mutator find(Key key) {
+        return Mutator(*this, key, false);
+    }
+
+    // Lookup without creating a temporary Mutator.
+    Value get(Key key) {
+        Hash hash = KeyTraits::hash(key);
+        TURF_TRACE(ConcurrentMap_Linear, 16, "[get] called", uptr(this), uptr(hash));
+        for (;;) {
+            typename Details::Table* table = m_root.load(turf::Consume);
+            typename Details::Cell* cell = Details::find(hash, table);
+            if (!cell)
+                return Value(ValueTraits::NullValue);
+            Value value = cell->value.load(turf::Consume);
+            if (value != Value(ValueTraits::Redirect))
+                return value;                        // Found an existing value
+            // We've been redirected to a new table. Help with the migration.
+            TURF_TRACE(ConcurrentMap_Linear, 17, "[get] was redirected", uptr(table), uptr(cell));
+            table->jobCoordinator.participate();
+            // Try again in the new table.
+        }
+    }
+
+    Value insert(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value exchange(Key key, Value desired) {
+        Mutator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value erase(Key key) {
+        Mutator iter(*this, key, false);
+        return iter.eraseValue();
+    }
+
+    // The easiest way to implement an Iterator is to prevent all Redirects.
+    // The currrent Iterator does that by forbidding concurrent inserts.
+    // To make it work with concurrent inserts, we'd need a way to block TableMigrations.
+    class Iterator {
+    private:
+        typename Details::Table* m_table;
+        ureg m_idx;
+        Key m_hash;
+        Value m_value;
+
+    public:
+        Iterator(ConcurrentMap_Linear& map) {
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            m_table = map.m_root.load(turf::Consume);
+            m_idx = -1;
+            next();
+        }
+
+        void next() {
+            TURF_ASSERT(m_table);
+            TURF_ASSERT(isValid() || m_idx == -1);  // Either the Iterator is already valid, or we've just started iterating.
+            while (++m_idx <= m_table->sizeMask) {
+                // Index still inside range of table.
+                typename Details::Cell *cell = m_table->getCells() + m_idx;
+                m_hash = cell->hash.load(turf::Relaxed);
+                if (m_hash != KeyTraits::NullHash) {
+                    // Cell has been reserved.
+                    m_value = cell->value.load(turf::Relaxed);
+                    TURF_ASSERT(m_value != Value(ValueTraits::Redirect));
+                    if (m_value != Value(ValueTraits::NullValue))
+                        return;     // Yield this cell.
+                }
+            }
+            // That's the end of the map.
+            m_hash = KeyTraits::NullHash;
+            m_value = ValueTraits::NullValue;
+        }
+
+        bool isValid() const {
+            return m_value != Value(ValueTraits::NullValue);
+        }
+
+        Key getKey() const {
+            TURF_ASSERT(isValid());
+            // Since we've forbidden concurrent inserts (for now), nonatomic would suffice here, but let's plan ahead:
+            return KeyTraits::dehash(m_hash);
+        }
+
+        Value getValue() const {
+            TURF_ASSERT(isValid());
+            return m_value;
+        }
+    };
+};
+
+} // namespace junction
+
+#endif // JUNCTION_CONCURRENTMAP_LINEAR_H
diff --git a/junction/Core.h b/junction/Core.h
new file mode 100644 (file)
index 0000000..aacc8a7
--- /dev/null
@@ -0,0 +1,33 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_CORE_H
+#define JUNCTION_CORE_H
+
+//-----------------------------------------------
+#include "junction_config.h"  // junction_config.h generated by CMake.
+
+// Default to true in case junction_config.h is missing entirely:
+#ifndef JUNCTION_USE_STRIPING
+#define JUNCTION_USE_STRIPING 1
+#endif
+//-----------------------------------------------
+
+#include <turf/Core.h>
+#include <turf/Assert.h>
+#include <turf/Atomic.h>
+
+namespace junction {
+using namespace turf::intTypes;
+}
+
+#endif // JUNCTION_CORE_H
diff --git a/junction/MapTraits.h b/junction/MapTraits.h
new file mode 100644 (file)
index 0000000..de83d27
--- /dev/null
@@ -0,0 +1,44 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_MAPTRAITS_H
+#define JUNCTION_MAPTRAITS_H
+
+#include <junction/Core.h>
+#include <turf/Util.h>
+
+namespace junction {
+
+template <class T>
+struct DefaultKeyTraits {
+    typedef T Key;
+    typedef typename turf::util::BestFit<T>::Unsigned Hash;
+    static const Hash NullHash = Hash(0);
+    static Hash hash(T key) {
+        return turf::util::avalanche(Hash(key));
+    }
+    static Key dehash(Hash hash) {
+        return (T) turf::util::deavalanche(hash);
+    }
+};
+
+template <class T>
+struct DefaultValueTraits {
+    typedef T Value;
+    typedef typename turf::util::BestFit<T>::Unsigned IntType;
+    static const IntType NullValue = 0;
+    static const IntType Redirect = 1;
+};
+
+} // namespace junction
+
+#endif // JUNCTION_MAPTRAITS_H
diff --git a/junction/QSBR.cpp b/junction/QSBR.cpp
new file mode 100644 (file)
index 0000000..eaab358
--- /dev/null
@@ -0,0 +1,107 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/QSBR.h>
+#include <turf/Thread.h>
+#include <turf/Mutex.h>
+#include <turf/RaceDetector.h>
+#include <unordered_map>
+#include <vector>
+
+namespace junction {
+
+QSBR DefaultQSBR;
+
+QSBR::Context QSBR::createContext() {
+    turf::LockGuard<turf::Mutex> guard(m_mutex);
+    TURF_RACE_DETECT_GUARD(m_flushRaceDetector);
+    m_numContexts++;
+    m_remaining++;
+    TURF_ASSERT(m_numContexts < (1 << 14));
+    sreg context = m_freeIndex;
+    if (context >= 0) {
+        TURF_ASSERT(context < (sreg) m_status.size());
+        TURF_ASSERT(!m_status[context].inUse);
+        m_freeIndex = m_status[context].nextFree;
+        m_status[context] = Status();
+    } else {
+        context = m_status.size();
+        m_status.push_back(Status());
+    }
+    return context;
+}
+
+void QSBR::destroyContext(QSBR::Context context) {
+    std::vector<Action> actions;
+    {
+        turf::LockGuard<turf::Mutex> guard(m_mutex);
+        TURF_RACE_DETECT_GUARD(m_flushRaceDetector);
+        TURF_ASSERT(context < m_status.size());
+        if (m_status[context].inUse && !m_status[context].wasIdle) {
+            TURF_ASSERT(m_remaining > 0);
+            --m_remaining;
+        }
+        m_status[context].inUse = 0;
+        m_status[context].nextFree = m_freeIndex;
+        m_freeIndex = context;
+        m_numContexts--;
+        if (m_remaining == 0)
+            onAllQuiescentStatesPassed(actions);
+    }
+    for (ureg i = 0; i < actions.size(); i++)
+        actions[i]();
+}
+
+void QSBR::onAllQuiescentStatesPassed(std::vector<Action>& actions) {
+    // m_mutex must be held
+    actions.swap(m_pendingActions);
+    m_pendingActions.swap(m_deferredActions);
+    m_remaining = m_numContexts;
+    for (ureg i = 0; i < m_status.size(); i++)
+        m_status[i].wasIdle = 0;
+}
+
+void QSBR::update(QSBR::Context context) {
+    std::vector<Action> actions;
+    {
+        turf::LockGuard<turf::Mutex> guard(m_mutex);
+        TURF_RACE_DETECT_GUARD(m_flushRaceDetector);
+        TURF_ASSERT(context < m_status.size());
+        Status& status = m_status[context];
+        TURF_ASSERT(status.inUse);
+        if (status.wasIdle)
+            return;
+        status.wasIdle = 1;
+        TURF_ASSERT(m_remaining > 0);
+        if (--m_remaining > 0)
+            return;
+        onAllQuiescentStatesPassed(actions);
+    }
+    for (ureg i = 0; i < actions.size(); i++)
+        actions[i]();
+}
+
+void QSBR::flush() {
+    // This is like saying that all contexts are quiescent,
+    // so we can issue all actions at once.
+    // No lock is taken.
+    TURF_RACE_DETECT_GUARD(m_flushRaceDetector);   // There should be no concurrent operations
+    for (ureg i = 0; i < m_pendingActions.size(); i++)
+        m_pendingActions[i]();
+    m_pendingActions.clear();
+    for (ureg i = 0; i < m_deferredActions.size(); i++)
+        m_deferredActions[i]();
+    m_deferredActions.clear();
+    m_remaining = m_numContexts;
+}
+
+} // namespace junction
diff --git a/junction/QSBR.h b/junction/QSBR.h
new file mode 100644 (file)
index 0000000..98a9a1b
--- /dev/null
@@ -0,0 +1,91 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_QSBR_H
+#define JUNCTION_QSBR_H
+
+#include <junction/Core.h>
+#include <turf/Mutex.h>
+#include <turf/RaceDetector.h>
+#include <vector>
+#include <string.h>
+
+namespace junction {
+
+class QSBR {
+private:
+    struct Action {
+        void (*func)(void*);
+        uptr param[4];      // Size limit found experimentally. Verified by assert below.
+
+        Action(void (*f)(void*), void* p, ureg paramSize) : func(f) {
+            TURF_ASSERT(paramSize <= sizeof(param));    // Verify size limit.
+            memcpy(&param, p, paramSize);
+        }
+        void operator()() {
+            func(&param);
+        }
+    };
+
+    struct Status {
+        u16 inUse : 1;
+        u16 wasIdle : 1;
+        s16 nextFree : 14;
+
+        Status() : inUse(1), wasIdle(0), nextFree(0) {
+        }
+    };
+
+    turf::Mutex m_mutex;
+    TURF_DEFINE_RACE_DETECTOR(m_flushRaceDetector)
+    std::vector<Status> m_status;
+    sreg m_freeIndex;
+    sreg m_numContexts;
+    sreg m_remaining;
+    std::vector<Action> m_deferredActions;
+    std::vector<Action> m_pendingActions;
+
+    void onAllQuiescentStatesPassed(std::vector<Action>& callbacks);
+
+public:
+    typedef u16 Context;
+
+    QSBR() : m_freeIndex(-1), m_numContexts(0), m_remaining(0) {
+    }
+    Context createContext();
+    void destroyContext(Context context);
+
+    template <class T>
+    void enqueue(void (T::*pmf)(), T* target) {
+        struct Closure {
+            void (T::*pmf)();
+            T* target;
+            static void thunk(void* param) {
+                Closure* self = (Closure*) param; 
+                TURF_CALL_MEMBER(*self->target, self->pmf)();
+            }
+        };
+        Closure closure = { pmf, target };
+        turf::LockGuard<turf::Mutex> guard(m_mutex);
+        TURF_RACE_DETECT_GUARD(m_flushRaceDetector);
+        m_deferredActions.push_back(Action(Closure::thunk, &closure, sizeof(closure)));
+    }
+
+    void update(Context context);
+    void flush();
+};
+
+extern QSBR DefaultQSBR;
+
+} // junction
+
+#endif // JUNCTION_QSBR_H
diff --git a/junction/SimpleJobCoordinator.h b/junction/SimpleJobCoordinator.h
new file mode 100644 (file)
index 0000000..2732497
--- /dev/null
@@ -0,0 +1,92 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_SIMPLEJOBCOORDINATOR_H
+#define JUNCTION_SIMPLEJOBCOORDINATOR_H
+
+#include <junction/Core.h>
+#include <junction/striped/ConditionBank.h>
+
+namespace junction {
+
+// It's safe to call everything here from within a Job itself.
+// In particular, you're allowed to particpate() recursively.
+// We actually do this in ConcurrentMap_Grampa::publish() when migrating a new flattree.
+class SimpleJobCoordinator {
+public:
+    struct Job {
+        virtual ~Job() {
+        }
+        virtual void run() = 0;
+    };
+
+private:
+    JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
+    turf::Atomic<uptr> m_job;
+
+public:
+    SimpleJobCoordinator() : m_job(uptr(NULL)) {
+    }
+
+    Job* loadConsume() const {
+        return (Job*) m_job.load(turf::Consume);
+    }
+
+    void storeRelease(Job* job) {
+        junction::striped::ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+        {
+            turf::LockGuard<turf::Mutex> guard(pair.mutex);
+            m_job.store(uptr(job), turf::Release);
+        }
+        pair.condVar.wakeAll();
+    }
+
+    void participate() {
+        junction::striped::ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+        uptr prevJob = uptr(NULL);
+        for (;;) {
+            uptr job = m_job.load(turf::Consume);
+            if (job == prevJob) {
+                turf::LockGuard<turf::Mutex> guard(pair.mutex);
+                for (;;) {
+                    job = m_job.loadNonatomic();    // No concurrent writes inside lock
+                    if (job != prevJob)
+                        break;
+                    pair.condVar.wait(guard);
+                }
+            }
+            if (job == 1)
+                return;
+            reinterpret_cast<Job*>(job)->run();
+            prevJob = job;
+        }
+    }
+
+    void runOne(Job* job) {
+        TURF_ASSERT(job != (Job*) m_job.load(turf::Relaxed));
+        storeRelease(job);
+        job->run();
+    }
+
+    void end() {
+        junction::striped::ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+        {
+            turf::LockGuard<turf::Mutex> guard(pair.mutex);
+            m_job.store(1, turf::Release);
+        }
+        pair.condVar.wakeAll();
+    }
+};
+
+} // namespace junction
+
+#endif // JUNCTION_SIMPLEJOBCOORDINATOR_H
diff --git a/junction/SingleMap_Linear.h b/junction/SingleMap_Linear.h
new file mode 100644 (file)
index 0000000..5ea2521
--- /dev/null
@@ -0,0 +1,207 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_SINGLEMAP_LINEAR_H
+#define JUNCTION_SINGLEMAP_LINEAR_H
+
+#include <junction/Core.h>
+#include <junction/MapTraits.h>
+#include <turf/Util.h>
+#include <turf/Heap.h>
+
+namespace junction {
+
+template <typename Key, typename Value, class KeyTraits = DefaultKeyTraits<Key>, class ValueTraits = DefaultValueTraits<Value>>
+class SingleMap_Linear {
+private:
+    typedef typename KeyTraits::Hash Hash;
+
+    struct Cell {
+        Hash hash;
+        Value value;
+        Cell(Hash hash, Value value) : hash(hash), value(value) {
+        }
+    };
+
+    Cell* m_cells;
+    u32 m_sizeMask;
+    u32 m_population;
+
+    static Cell* createTable(ureg size) {
+        Cell* cells = (Cell*) TURF_HEAP.alloc(sizeof(Cell) * size);
+        for (ureg i = 0; i < size; i++)
+            new(cells + i) Cell(KeyTraits::NullHash, Value(ValueTraits::NullValue));
+        return cells;
+    }
+
+    static void destroyTable(Cell* cells, ureg size) {
+        for (ureg i = 0; i < size; i++)
+            cells[i].~Cell();
+        TURF_HEAP.free(cells);
+    }
+
+    static bool isOverpopulated(ureg population, ureg sizeMask) {
+        return (population * 4) >= (sizeMask * 3);
+    }
+
+    void migrateToNewTable(size_t desiredSize) {
+        TURF_ASSERT(turf::util::isPowerOf2(desiredSize));
+        Cell* srcCells = m_cells;
+        ureg srcSize = m_sizeMask + 1;
+        m_cells = createTable(desiredSize);
+        m_sizeMask = desiredSize - 1;
+        for (ureg srcIdx = 0; srcIdx < srcSize; srcIdx++) {
+            Cell* srcCell = srcCells + srcIdx;
+            if (srcCell->hash != KeyTraits::NullHash) {
+                for (ureg dstIdx = srcCell->hash;; dstIdx++) {
+                    dstIdx &= m_sizeMask;
+                    if (m_cells[dstIdx].hash == KeyTraits::NullHash) {
+                        m_cells[dstIdx] = *srcCell;
+                        break;
+                    }
+                }
+            }
+        }
+        destroyTable(srcCells, srcSize);
+    }
+
+public:
+    SingleMap_Linear(size_t initialSize = 8) : m_cells(createTable(initialSize)), m_sizeMask(initialSize - 1), m_population(0) {
+        TURF_ASSERT(turf::util::isPowerOf2(initialSize));
+    }
+
+    ~SingleMap_Linear() {
+        destroyTable(m_cells, m_sizeMask + 1);
+    }
+
+    class Iterator {
+    private:
+        friend class SingleMap_Linear;
+        SingleMap_Linear& m_map;
+        Cell* m_cell;
+
+        // Constructor: Find without insert
+        Iterator(SingleMap_Linear& map, Key key, bool) : m_map(map) {
+            Hash hash = KeyTraits::hash(key);
+            TURF_ASSERT(hash != KeyTraits::NullHash);
+            for (ureg idx = hash;; idx++) {
+                idx &= map.m_sizeMask;
+                m_cell = map.m_cells + idx;
+                if (m_cell->hash == hash)
+                    return;         // Key found in table.
+                if (m_cell->hash != KeyTraits::NullHash)
+                    continue;       // Slot is taken by another key. Try next slot.
+                m_cell = NULL;  // Insert not allowed & key not found.
+                return;
+            }
+        }
+
+        // Constructor: Find with insert
+        Iterator(SingleMap_Linear& map, Key key) : m_map(map) {
+            Hash hash = KeyTraits::hash(key);
+            TURF_ASSERT(hash != KeyTraits::NullHash);
+            for (;;) {
+                for (ureg idx = hash;; idx++) {
+                    idx &= map.m_sizeMask;
+                    m_cell = map.m_cells + idx;
+                    if (m_cell->hash == hash)
+                        return;         // Key found in table.
+                    if (m_cell->hash != KeyTraits::NullHash)
+                        continue;       // Slot is taken by another key. Try next slot.
+                    // Insert is allowed. Reserve this cell.
+                    if (isOverpopulated(map.m_population, map.m_sizeMask)) {
+                        map.migrateToNewTable((map.m_sizeMask + 1) * 2);
+                        break;          // Retry in new table.
+                    }
+                    map.m_population++;
+                    m_cell->hash = hash;
+                    TURF_ASSERT(m_cell->value == NULL);
+                    return;
+                }
+            }
+        }
+
+        ~Iterator() {
+            TURF_ASSERT(!m_cell || m_cell->value != NULL);  // Forbid leaving a cell half-inserted.
+        }
+
+    public:
+        bool isValid() const {
+            return !!m_cell;
+        }
+
+        Value getValue() const {
+            TURF_ASSERT(m_cell);
+            return m_cell->value;
+        }
+
+        Value exchangeValue(Value desired) {
+            TURF_ASSERT(m_cell);
+            TURF_ASSERT(desired != NULL);  // Use eraseValue()
+            Value oldValue = m_cell->value;
+            m_cell->value = desired;
+            return oldValue;
+        }
+
+        Value erase() {
+            TURF_ASSERT(m_cell);
+            TURF_ASSERT(m_cell->value != NULL);  // Forbid erasing a cell that's not actually used.
+            Value oldValue = m_cell->value;
+            // Remove this cell by shuffling neighboring cells so there are no gaps in anyone's probe chain
+            ureg cellIdx = m_cell - m_map.m_cells; 
+            for (ureg neighborIdx = cellIdx + 1;; neighborIdx++) {
+                neighborIdx &= m_map.m_sizeMask;
+                Cell* neighbor = m_map.m_cells + neighborIdx;
+                if (neighbor->hash == KeyTraits::NullHash) {
+                    // Go ahead and clear this cell. It won't break anyone else's probe chain.
+                    m_cell->hash = KeyTraits::NullHash;
+                    m_cell->value = NULL;
+                    m_cell = NULL;
+                    m_map.m_population--;
+                    return oldValue;
+                }
+                ureg idealIdx = neighbor->hash & m_map.m_sizeMask;
+                if (((cellIdx - idealIdx) & m_map.m_sizeMask) < ((neighborIdx - idealIdx) & m_map.m_sizeMask)) {
+                    // Swap with neighbor, then make neighbor the new cell to remove.
+                    *m_cell = *neighbor;
+                    m_cell = neighbor;
+                    cellIdx = neighborIdx;
+                }
+            }
+        }
+    };
+
+    Iterator insertOrFindKey(const Key& key) {
+        return Iterator(*this, key);
+    }
+
+    Value get(const Key& key) {
+        Iterator iter(*this, key, false);
+        return iter.isValid() ? iter.getValue() : NULL;
+    }
+
+    Value insert(const Key& key, Value desired) {
+        Iterator iter(*this, key);
+        return iter.exchangeValue(desired);
+    }
+
+    Value erase(const Key& key) {
+        Iterator iter(*this, key, false);
+        if (iter.isValid())
+            return iter.erase();
+        return NULL;
+    }
+};
+
+} // namespace junction
+
+#endif // JUNCTION_SINGLEMAP_LINEAR_H
diff --git a/junction/details/Grampa.cpp b/junction/details/Grampa.cpp
new file mode 100644 (file)
index 0000000..3b33fa5
--- /dev/null
@@ -0,0 +1,65 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <junction/details/Grampa.h>
+#include <turf/Heap.h>
+
+namespace junction {
+namespace details {
+
+#if JUNCTION_TRACK_GRAMPA_STATS
+GrampaStats GrampaStats::Instance;
+#endif
+
+TURF_TRACE_DEFINE_BEGIN(Grampa, 37) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[find] called")
+TURF_TRACE_DEFINE("[find] found existing cell optimistically")
+TURF_TRACE_DEFINE("[find] found existing cell")
+TURF_TRACE_DEFINE("[insert] called")
+TURF_TRACE_DEFINE("[insert] reserved first cell")
+TURF_TRACE_DEFINE("[insert] race to reserve first cell")
+TURF_TRACE_DEFINE("[insert] found in first cell")
+TURF_TRACE_DEFINE("[insert] race to read hash")
+TURF_TRACE_DEFINE("[insert] found in probe chain")
+TURF_TRACE_DEFINE("[insert] reserved cell")
+TURF_TRACE_DEFINE("[insert] race to reserve cell")
+TURF_TRACE_DEFINE("[insert] found outside probe chain")
+TURF_TRACE_DEFINE("[insert] found late-arriving cell in same bucket")
+TURF_TRACE_DEFINE("[insert] set link on behalf of late-arriving cell")
+TURF_TRACE_DEFINE("[insert] overflow")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] called")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] new migration already exists")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] new migration already exists (double-checked)")
+TURF_TRACE_DEFINE("[beginTableMigration] redirected while determining table size")
+TURF_TRACE_DEFINE("[migrateRange] empty cell already redirected")
+TURF_TRACE_DEFINE("[migrateRange] race to insert key")
+TURF_TRACE_DEFINE("[migrateRange] race to insert value")
+TURF_TRACE_DEFINE("[migrateRange] race inserted Redirect")
+TURF_TRACE_DEFINE("[migrateRange] in-use cell already redirected")
+TURF_TRACE_DEFINE("[migrateRange] racing update was erase")
+TURF_TRACE_DEFINE("[migrateRange] race to update migrated value")
+TURF_TRACE_DEFINE("[TableMigration::run] already ended")
+TURF_TRACE_DEFINE("[TableMigration::run] detected end flag set")
+TURF_TRACE_DEFINE("[TableMigration::run] destination overflow")
+TURF_TRACE_DEFINE("[TableMigration::run] race to set m_overflowTableIndex")
+TURF_TRACE_DEFINE("[TableMigration::run] out of migration units")
+TURF_TRACE_DEFINE("[TableMigration::run] not the last worker")
+TURF_TRACE_DEFINE("[TableMigration::run] a new TableMigration was already started")
+TURF_TRACE_DEFINE("[TableMigration::run] overflow occured in a small map")
+TURF_TRACE_DEFINE("[TableMigration::run] doubling subtree size after failure")
+TURF_TRACE_DEFINE("[TableMigration::run] keeping same subtree size after failure")
+TURF_TRACE_DEFINE("[FlatTreeMigration::run] already ended")
+TURF_TRACE_DEFINE_END(Grampa, 37)
+
+} // namespace details
+} // namespace junction
diff --git a/junction/details/Grampa.h b/junction/details/Grampa.h
new file mode 100644 (file)
index 0000000..b44a8c4
--- /dev/null
@@ -0,0 +1,875 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_DETAILS_GRAMPA_H
+#define JUNCTION_DETAILS_GRAMPA_H
+
+#include <junction/Core.h>
+#include <turf/Atomic.h>
+#include <junction/striped/Mutex.h>
+#include <junction/striped/ManualResetEvent.h>
+#include <turf/Util.h>
+#include <junction/MapTraits.h>
+#include <turf/Trace.h>
+#include <turf/Heap.h>
+#include <junction/SimpleJobCoordinator.h>
+#include <junction/QSBR.h>
+#include <memory.h>
+
+namespace junction {
+namespace details {
+
+#if JUNCTION_TRACK_GRAMPA_STATS
+struct GrampaCounter {
+    turf::Atomic<ureg> total;
+    turf::Atomic<sreg> current;
+
+    void increment() {
+        total.fetchAdd(1, turf::Relaxed);
+        current.fetchAdd(1, turf::Relaxed);
+    }
+
+    void decrement() {
+        current.fetchSub(1, turf::Relaxed);
+    }
+};
+
+struct GrampaStats {
+    GrampaCounter numTables;
+    GrampaCounter numTableMigrations;
+    GrampaCounter numFlatTrees;
+    GrampaCounter numFlatTreeMigrations;
+
+    static GrampaStats Instance;    // Zero-initialized
+};
+#endif
+
+TURF_TRACE_DECLARE(Grampa, 37)
+
+template<class Map>
+struct Grampa {
+    typedef typename Map::Hash Hash;
+    typedef typename Map::Value Value;
+    typedef typename Map::KeyTraits KeyTraits;
+    typedef typename Map::ValueTraits ValueTraits;
+
+    static const ureg RedirectFlatTree = 1;
+    static const ureg InitialSize = 8;
+    static const ureg TableMigrationUnitSize = 32;
+    static const ureg FlatTreeMigrationUnitSize = 32;
+    static const ureg LinearSearchLimit = 128;
+    static const ureg CellsInUseSample = LinearSearchLimit;
+    TURF_STATIC_ASSERT(LinearSearchLimit > 0 && LinearSearchLimit < 256); // Must fit in CellGroup::links
+    TURF_STATIC_ASSERT(CellsInUseSample > 0 && CellsInUseSample <= LinearSearchLimit); // Limit sample to failed search chain
+
+    static const ureg MinTableSize = 8;
+    static const ureg LeafSizeBits = 10;
+    static const ureg LeafSize = (ureg(1) << LeafSizeBits);
+
+    struct Cell {
+        // If value == Redirect, threads participate in the jobCoordinator.
+        turf::Atomic<Hash> hash;
+        turf::Atomic<Value> value;
+    };
+
+    struct CellGroup {
+        // Every cell in the table actually represents a bucket of cells, all linked together in a probe chain.
+        // Each cell in the probe chain is located within the table itself.
+        // "deltas" determines the index of the next cell in the probe chain.
+        // The first cell in the chain is the one that was hashed. It may or may not actually belong in the bucket.
+        // The "second" cell in the chain is given by deltas 0 - 3. It's guaranteed to belong in the bucket.
+        // All subsequent cells in the chain is given by deltas 4 - 7. Also guaranteed to belong in the bucket.
+        turf::Atomic<u8> deltas[8];
+        Cell cells[4];
+    };
+
+    struct Table {
+        // unsafeRangeShift determines how many slots are occupied by this Table in the flattree.
+        // The range of hashes stored in this table is given by (1 << shift).
+        // eg. If the entire map is stored in a single table, then Table::shift == HASH_BITS.
+        // If the entire map is stored in two tables, then Table::shift == (HASH_BITS - 1) for each table.
+        // FlatTree::shift is always <= Table::shift for all the tables it contains.
+        const ureg sizeMask;                            // a power of two minus one
+        const Hash baseHash;
+        const ureg unsafeRangeShift;
+        junction::striped::ManualResetEvent isPublished;    // To prevent publishing a subtree before its parent is published (happened in testing)
+        junction::striped::Mutex mutex;                     // to DCLI the TableMigration (stored in the jobCoordinator)
+        SimpleJobCoordinator jobCoordinator;            // makes all blocked threads participate in the migration
+
+        Table(ureg sizeMask, Hash baseHash, ureg unsafeRangeShift) : sizeMask(sizeMask), baseHash(baseHash), unsafeRangeShift(unsafeRangeShift) {
+        }
+
+        static Table* create(ureg tableSize, ureg baseHash, ureg unsafeShift) {
+            TURF_ASSERT(turf::util::isPowerOf2(tableSize));
+            TURF_ASSERT(unsafeShift > 0 && unsafeShift <= sizeof(Hash) * 8);
+            TURF_ASSERT(tableSize >= 4);
+            ureg numGroups = tableSize >> 2;
+            Table* table = (Table*) TURF_HEAP.alloc(sizeof(Table) + sizeof(CellGroup) * numGroups);
+            new(table) Table(tableSize - 1, baseHash, (u8) unsafeShift);
+            for (ureg i = 0; i < numGroups; i++) {
+                CellGroup* group = table->getCellGroups() + i;
+                for (ureg j = 0; j < 4; j++) {
+                    group->deltas[j].storeNonatomic(0);
+                    group->deltas[j + 4].storeNonatomic(0);
+                    group->cells[j].hash.storeNonatomic(KeyTraits::NullHash);
+                    group->cells[j].value.storeNonatomic(Value(ValueTraits::NullValue));
+                }
+            }
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numTables.increment();
+#endif
+            return table;
+        }
+
+        void destroy() {
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numTables.decrement();
+#endif
+            this->Table::~Table();
+            TURF_HEAP.free(this);
+        }
+
+        CellGroup* getCellGroups() const {
+            return (CellGroup*) (this + 1);
+        }
+
+        ureg getNumMigrationUnits() const {
+            return sizeMask / TableMigrationUnitSize + 1;
+        }
+    };
+
+    class TableMigration : public SimpleJobCoordinator::Job {
+    public:
+        struct Source {
+            Table* table;
+            turf::Atomic<ureg> sourceIndex;
+        };
+
+        Map& m_map;
+        Hash m_baseHash;                           // The lowest possible hash value in this subtree; determines index in flattree.
+        // If m_numDestinations == 1, m_shift == 0.
+        // Otherwise, m_shift tells (indirectly) the size of the flattree in which our subtree would exactly fit: 1 << (HASH_BITS - m_shift).
+        // This ensures that m_shift is always less than sizeof(Hash) * 8, so that shifting by m_shift is not undefined behavior.
+        // To determine the subtree index for a hash during migration, we use: (hash >> m_shift) & (m_numDestinations - 1)
+        // A mask is used since we are only migrating a subtree -- not necessarily the entire map.
+        ureg m_safeShift;
+        turf::Atomic<ureg> m_workerStatus;          // number of workers + end flag
+        turf::Atomic<sreg> m_overflowTableIndex;
+        turf::Atomic<sreg> m_unitsRemaining;
+        ureg m_numSources;
+        ureg m_numDestinations;                 // The size of the subtree being created. Some table pointers may be repeated.
+
+        TableMigration(Map& map) : m_map(map) {
+        }
+
+        static TableMigration* create(Map& map, ureg numSources, ureg numDestinations) {
+            TableMigration* migration = (TableMigration*) TURF_HEAP.alloc(sizeof(TableMigration) + sizeof(TableMigration::Source) * numSources + sizeof(Table*) * numDestinations);
+            new(migration) TableMigration(map);
+            migration->m_workerStatus.storeNonatomic(0);
+            migration->m_overflowTableIndex.storeNonatomic(-1);
+            migration->m_unitsRemaining.storeNonatomic(0);
+            migration->m_numSources = numSources;
+            migration->m_numDestinations = numDestinations;
+            // Caller is responsible for filling in source & destination pointers
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numTableMigrations.increment();
+#endif
+            return migration;
+        }
+
+        virtual ~TableMigration() TURF_OVERRIDE {
+        }
+
+        void destroy() {
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numTableMigrations.decrement();
+#endif
+            // Destroy all source tables.
+            for (ureg i = 0; i < m_numSources; i++)
+                if (getSources()[i].table)
+                    getSources()[i].table->destroy();
+            // Delete the migration object itself.
+            this->TableMigration::~TableMigration();
+            TURF_HEAP.free(this);
+        }
+
+        ureg getUnsafeShift() const {
+            return m_safeShift ? m_safeShift : (sizeof(Hash) * 8);
+        }
+
+        Source* getSources() const {
+            return (Source*) (this + 1);
+        }
+
+        Table** getDestinations() const {
+            return (Table**) (getSources() + m_numSources);
+        }
+
+        sreg migrateRange(Table* srcTable, ureg startIdx);
+        virtual void run() TURF_OVERRIDE;
+    };
+
+    class FlatTreeMigration;
+
+    struct FlatTree {
+        // The size of the flattree is 1 << 64 - HASH_BITS.
+        // Or, stated another way, (Hash(-1) >> shift) + 1.
+        // To determine the flattree index for a given hash, we simply use: (hash >> shift)
+        // Smaller shift == more significant bits used as an index == bigger flattree.
+        // For example, the simplest flattree has only two entries, and only the most significant
+        // bit of each hash is used as the flattree index. In that case, shift == HASH_BITS - 1.
+        // Each time the flattree doubles in size, shift decreases by 1.
+        const ureg safeShift;
+        junction::striped::Mutex mutex;
+        FlatTreeMigration* migration;   // Protected by mutex
+
+        FlatTree(ureg safeShift) : safeShift(safeShift), migration(NULL) {
+            // A FlatTree always has at least two tables, so the shift is always safe.
+            TURF_ASSERT(safeShift < sizeof(Hash) * 8);
+        }
+
+        static FlatTree* create(ureg safeShift) {
+            // A flattree always has at least two tables, so the shift is always safe.
+            TURF_ASSERT(safeShift < sizeof(Hash) * 8);
+            ureg numLeaves = (Hash(-1) >> safeShift) + 1;
+            FlatTree* flatTree = (FlatTree*) TURF_HEAP.alloc(sizeof(FlatTree) + sizeof(turf::Atomic<Table*>) * numLeaves);
+            new(flatTree) FlatTree(safeShift);
+            // Caller will initialize flatTree->getTables()
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numFlatTrees.increment();
+#endif
+            return flatTree;
+        }
+
+        void destroy() {
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numFlatTrees.decrement();
+#endif
+            this->FlatTree::~FlatTree();
+            TURF_HEAP.free(this);
+        }
+
+        turf::Atomic<Table*>* getTables() const {
+            return (turf::Atomic<Table*>*) (this + 1);
+        }
+
+        ureg getSize() const {
+            return (Hash(-1) >> safeShift) + 1;
+        }
+
+        ureg getNumMigrationUnits() const {
+            ureg sizeMask = Hash(-1) >> safeShift;
+            return sizeMask / FlatTreeMigrationUnitSize + 1;
+        }
+    };
+
+    class FlatTreeMigration : public SimpleJobCoordinator::Job {
+    public:
+        Map& m_map;
+        FlatTree* m_source;
+        FlatTree* m_destination;
+        turf::Atomic<ureg> m_workerStatus;
+        turf::Atomic<ureg> m_sourceIndex;
+        turf::Atomic<sreg> m_unitsRemaining;
+        junction::striped::ManualResetEvent m_completed;
+
+        FlatTreeMigration(Map& map, FlatTree* flatTree, ureg shift) : m_map(map) {
+            m_source = flatTree;
+            m_destination = FlatTree::create(shift);
+            m_workerStatus.storeNonatomic(0);
+            m_sourceIndex.storeNonatomic(0);
+            m_unitsRemaining.storeNonatomic(flatTree->getNumMigrationUnits());
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numFlatTreeMigrations.increment();
+#endif
+        }
+
+        virtual ~FlatTreeMigration() TURF_OVERRIDE {
+#if JUNCTION_TRACK_GRAMPA_STATS
+            GrampaStats::Instance.numFlatTreeMigrations.decrement();
+#endif
+            // Delete source flattree.
+            m_source->destroy();
+        }
+
+        void destroy() {
+            delete this;
+        }
+
+        virtual void run() TURF_OVERRIDE;
+    };
+
+    static void garbageCollectTable(Table* table) {
+        TURF_ASSERT(table);
+        DefaultQSBR.enqueue(&Table::destroy, table);
+    }
+
+    static void garbageCollectFlatTree(FlatTree* flatTree) {
+        TURF_ASSERT(flatTree);
+        DefaultQSBR.enqueue(&FlatTree::destroy, flatTree);
+    }
+
+    static Cell* find(Hash hash, Table* table, ureg sizeMask) {
+        TURF_TRACE(Grampa, 0, "[find] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        // Optimistically check hashed cell even though it might belong to another bucket
+        ureg idx = hash & sizeMask;
+        CellGroup* group = table->getCellGroups() + (idx >> 2);
+        Cell* cell = group->cells + (idx & 3);
+        Hash probeHash = cell->hash.load(turf::Relaxed);
+        if (probeHash == hash) {
+            TURF_TRACE(Grampa, 1, "[find] found existing cell optimistically", uptr(table), idx);
+            return cell;
+        } else if (probeHash == KeyTraits::NullHash) {
+            return cell = NULL;
+        }
+        // Follow probe chain for our bucket
+        u8 delta = group->deltas[idx & 3].load(turf::Relaxed);
+        while (delta) {
+            idx = (idx + delta) & sizeMask;
+            group = table->getCellGroups() + (idx >> 2);
+            cell = group->cells + (idx & 3);
+            Hash probeHash = cell->hash.load(turf::Relaxed);
+            // Note: probeHash might actually be NULL due to memory reordering of a concurrent insert,
+            // but we don't check for it. We just follow the probe chain.
+            if (probeHash == hash) {
+                TURF_TRACE(Grampa, 2, "[find] found existing cell", uptr(table), idx);
+                return cell;
+            }
+            delta = group->deltas[(idx & 3) + 4].load(turf::Relaxed);
+        }
+        // End of probe chain, not found
+        return NULL;
+    }
+
+    // FIXME: Possible optimization: Dedicated insert for migration? It wouldn't check for InsertResult_AlreadyFound.
+    enum InsertResult {
+        InsertResult_AlreadyFound,
+        InsertResult_InsertedNew,
+        InsertResult_Overflow
+    };
+    static InsertResult insert(Hash hash, Table* table, ureg sizeMask, Cell*& cell, ureg& overflowIdx) {
+        TURF_TRACE(Grampa, 3, "[insert] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        ureg idx = hash;
+
+        // Check hashed cell first, though it may not even belong to the bucket.
+        CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+        cell = group->cells + (idx & 3);
+        Hash probeHash = cell->hash.load(turf::Relaxed);
+        if (probeHash == KeyTraits::NullHash) {
+            if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
+                TURF_TRACE(Grampa, 4, "[insert] reserved first cell", uptr(table), idx);
+                // There are no links to set. We're done.
+                return InsertResult_InsertedNew;
+            } else {
+                TURF_TRACE(Grampa, 5, "[insert] race to reserve first cell", uptr(table), idx);
+                // Fall through to check if it was the same hash...
+            }
+        }
+        if (probeHash == hash) {
+            TURF_TRACE(Grampa, 6, "[insert] found in first cell", uptr(table), idx);
+            return InsertResult_AlreadyFound;
+        }
+
+        // Follow the link chain for this bucket.
+        ureg maxIdx = idx + sizeMask;
+        ureg linkLevel = 0;
+        turf::Atomic<u8>* prevLink;
+        for (;;) {
+        followLink:
+            prevLink = group->deltas + ((idx & 3) + linkLevel);
+            linkLevel = 4;
+            u8 probeDelta = prevLink->load(turf::Relaxed);
+            if (probeDelta) {
+                idx += probeDelta;
+                // Check the hash for this cell.
+                group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+                cell = group->cells + (idx & 3);
+                probeHash = cell->hash.load(turf::Relaxed);
+                if (probeHash == KeyTraits::NullHash) {
+                    // Cell was linked, but hash is not visible yet.
+                    // We could avoid this case (and guarantee it's visible) using acquire & release, but instead,
+                    // just poll until it becomes visible.
+                    TURF_TRACE(Grampa, 7, "[insert] race to read hash", uptr(table), idx);
+                    do {
+                        probeHash = cell->hash.load(turf::Acquire);
+                    } while (probeHash == KeyTraits::NullHash);
+                }
+                TURF_ASSERT(((probeHash ^ hash) & sizeMask) == 0);   // Only hashes in same bucket can be linked
+                if (probeHash == hash) {
+                    TURF_TRACE(Grampa, 8, "[insert] found in probe chain", uptr(table), idx);
+                    return InsertResult_AlreadyFound;
+                }
+            } else {
+                // Reached the end of the link chain for this bucket.
+                // Switch to linear probing until we reserve a new cell or find a late-arriving cell in the same bucket.
+                ureg prevLinkIdx = idx;
+                TURF_ASSERT(sreg(maxIdx - idx) >= 0);    // Nobody would have linked an idx that's out of range.
+                ureg linearProbesRemaining = turf::util::min(maxIdx - idx, LinearSearchLimit);
+                while (linearProbesRemaining-- > 0) {
+                    idx++;
+                    group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+                    cell = group->cells + (idx & 3);
+                    probeHash = cell->hash.load(turf::Relaxed);
+                    if (probeHash == KeyTraits::NullHash) {
+                        // It's an empty cell. Try to reserve it.
+                        if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
+                            // Success. We've reserved the cell. Link it to previous cell in same bucket.
+                            TURF_TRACE(Grampa, 9, "[insert] reserved cell", uptr(table), idx);
+                            TURF_ASSERT(probeDelta == 0);
+                            u8 desiredDelta = idx - prevLinkIdx;
+                            // Note: another thread could actually set the link on our behalf (see below).
+#if TURF_WITH_ASSERTS                            
+                            probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
+                            TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
+#else
+                            prevLink->store(desiredDelta, turf::Relaxed);
+#endif                            
+                            return InsertResult_InsertedNew;
+                        } else {
+                            TURF_TRACE(Grampa, 10, "[insert] race to reserve cell", uptr(table), idx);
+                            // Fall through to check if it's the same hash...
+                        }
+                    }
+                    Hash x = (probeHash ^ hash);
+                    // Check for same hash.
+                    if (!x) {
+                        TURF_TRACE(Grampa, 11, "[insert] found outside probe chain", uptr(table), idx);
+                        return InsertResult_AlreadyFound;
+                    }
+                    // Check for same bucket.
+                    if ((x & sizeMask) == 0) {
+                        TURF_TRACE(Grampa, 12, "[insert] found late-arriving cell in same bucket", uptr(table), idx);
+                        // Attempt to set the link on behalf of the late-arriving cell.
+                        // This is usually redundant, but if we don't attempt to set the late-arriving cell's link here,
+                        // there's no guarantee that our own link chain will be well-formed by the time this function returns.
+                        // (Indeed, subsequent lookups sometimes failed during testing, for this exact reason.)
+                        u8 desiredDelta = idx - prevLinkIdx;
+#if TURF_WITH_ASSERTS                            
+                        probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
+                        TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
+                        if (probeDelta == 0)
+                            TURF_TRACE(Grampa, 13, "[insert] set link on behalf of late-arriving cell", uptr(table), idx);
+#else
+                        prevLink->store(desiredDelta, turf::Relaxed);
+#endif                    
+                        goto followLink;  // Try to follow link chain for the bucket again.
+                    }
+                    // Continue linear search...
+                }
+                // Table is too full to insert.
+                overflowIdx = idx + 1;
+                TURF_TRACE(Grampa, 14, "[insert] overflow", uptr(table), overflowIdx);
+                return InsertResult_Overflow;
+            }
+        }
+    }
+
+    static void beginTableMigrationToSize(Map& map, Table* table, ureg nextTableSize, ureg splitShift) {
+        // Create new migration by DCLI.
+        TURF_TRACE(Grampa, 15, "[beginTableMigrationToSize] called", 0, 0);
+        SimpleJobCoordinator::Job* job = table->jobCoordinator.loadConsume();
+        if (job) {
+            TURF_TRACE(Grampa, 16, "[beginTableMigrationToSize] new migration already exists", 0, 0);
+        } else {
+            turf::LockGuard<junction::striped::Mutex> guard(table->mutex);
+            job = table->jobCoordinator.loadConsume();  // Non-atomic would be sufficient, but that's OK.
+            if (job) {
+                TURF_TRACE(Grampa, 17, "[beginTableMigrationToSize] new migration already exists (double-checked)", 0, 0);
+            } else {
+                // Create new migration.
+                ureg numDestinations = ureg(1) << splitShift;
+                TableMigration* migration = TableMigration::create(map, 1, numDestinations);
+                migration->m_baseHash = table->baseHash;
+                ureg migrationShift = table->unsafeRangeShift - splitShift;
+                migration->m_safeShift = (migrationShift < sizeof(Hash) * 8) ? migrationShift : 0;
+                migration->m_unitsRemaining.storeNonatomic(table->getNumMigrationUnits());
+                migration->getSources()[0].table = table;
+                migration->getSources()[0].sourceIndex.storeNonatomic(0);
+                ureg subRangeShift = table->unsafeRangeShift - splitShift;      // subRangeShift is also "unsafe" (possibly represents entire range)
+                ureg hashOffsetDelta = subRangeShift < (sizeof(Hash) * 8) ? (ureg(1) << subRangeShift) : 0;
+                for (ureg i = 0; i < numDestinations; i++) {
+                    migration->getDestinations()[i] = Table::create(nextTableSize, table->baseHash + hashOffsetDelta * i, subRangeShift);
+                }
+                // Publish the new migration.
+                table->jobCoordinator.storeRelease(migration);
+            }
+        }
+    }
+
+    static void beginTableMigration(Map& map, Table* table, ureg overflowIdx) {
+        // Estimate number of cells in use based on a small sample.
+        ureg sizeMask = table->sizeMask;
+        ureg idx = overflowIdx - CellsInUseSample;
+        ureg inUseCells = 0;
+        for (ureg linearProbesRemaining = CellsInUseSample; linearProbesRemaining > 0; linearProbesRemaining--) {
+            CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+            Cell* cell = group->cells + (idx & 3);
+            Value value = cell->value.load(turf::Relaxed);
+            if (value == Value(ValueTraits::Redirect)) {
+                // Another thread kicked off the jobCoordinator. The caller will participate upon return.
+                TURF_TRACE(Grampa, 18, "[beginTableMigration] redirected while determining table size", 0, 0);
+                return;
+            }
+            if (value != Value(ValueTraits::NullValue))
+                inUseCells++;
+            idx++;
+        }
+        float inUseRatio = float(inUseCells) / CellsInUseSample;
+        float estimatedInUse = (sizeMask + 1) * inUseRatio;
+        ureg nextTableSize = turf::util::roundUpPowerOf2(ureg(estimatedInUse * 2));
+        // FIXME: Support migrating to smaller tables.
+        nextTableSize = turf::util::max(nextTableSize, sizeMask + 1);
+        // Split into multiple tables if necessary.
+        ureg splitShift = 0;
+        while (nextTableSize > LeafSize) {
+            splitShift++;
+            nextTableSize >>= 1;
+        }
+        beginTableMigrationToSize(map, table, nextTableSize, splitShift);
+    }
+    
+    static FlatTreeMigration* createFlatTreeMigration(Map& map, FlatTree* flatTree, ureg shift) {
+        turf::LockGuard<junction::striped::Mutex> guard(flatTree->mutex);
+        if (!flatTree->migration) {
+            flatTree->migration = new FlatTreeMigration(map, flatTree, shift);
+        }
+        return flatTree->migration;
+    }
+
+    static FlatTreeMigration* getExistingFlatTreeMigration(FlatTree* flatTree) {
+        turf::LockGuard<junction::striped::Mutex> guard(flatTree->mutex);
+        TURF_ASSERT(flatTree->migration);     // Must already exist!
+        return flatTree->migration;
+    }
+}; // Grampa
+
+// Return index of the destination table that overflowed, or -1 if none
+template<class Map>
+sreg Grampa<Map>::TableMigration::migrateRange(Table* srcTable, ureg startIdx) {
+    ureg srcSizeMask = srcTable->sizeMask;
+    ureg safeShift = m_safeShift;
+    Table** dstLeafs = getDestinations();
+    ureg dstLeafMask = m_numDestinations - 1;
+    ureg endIdx = turf::util::min(startIdx + TableMigrationUnitSize, srcSizeMask + 1);
+    // Iterate over source range.
+    for (ureg srcIdx = startIdx; srcIdx < endIdx; srcIdx++) {
+        CellGroup* srcGroup = srcTable->getCellGroups() + ((srcIdx & srcSizeMask) >> 2);
+        Cell* srcCell = srcGroup->cells + (srcIdx & 3);
+        Hash srcHash;
+        Value srcValue;
+        // Fetch the srcHash and srcValue.
+        for (;;) {
+            srcHash = srcCell->hash.load(turf::Relaxed);
+            if (srcHash == KeyTraits::NullHash) {
+                // An unused cell. Try to put a Redirect marker in its value.
+                srcValue = srcCell->value.compareExchange(Value(ValueTraits::NullValue), Value(ValueTraits::Redirect), turf::Relaxed);
+                if (srcValue == Value(ValueTraits::Redirect)) {
+                    // srcValue is already marked Redirect due to previous incomplete migration.
+                    TURF_TRACE(Grampa, 19, "[migrateRange] empty cell already redirected", uptr(srcTable), srcIdx);
+                    break;
+                }
+                if (srcValue == Value(ValueTraits::NullValue))
+                    break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                TURF_TRACE(Grampa, 20, "[migrateRange] race to insert key", uptr(srcTable), srcIdx);
+                // Otherwise, somebody just claimed the cell. Read srcHash again...
+            } else {
+                // Check for deleted/uninitialized value.
+                srcValue = srcCell->value.load(turf::Relaxed);
+                if (srcValue == Value(ValueTraits::NullValue)) {
+                    // Try to put a Redirect marker.
+                    if (srcCell->value.compareExchangeStrong(srcValue, Value(ValueTraits::Redirect), turf::Relaxed))
+                        break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                    TURF_TRACE(Grampa, 21, "[migrateRange] race to insert value", uptr(srcTable), srcIdx);
+                    if (srcValue == Value(ValueTraits::Redirect)) {
+                        // FIXME: I don't think this will happen. Investigate & change to assert
+                        TURF_TRACE(Grampa, 22, "[migrateRange] race inserted Redirect", uptr(srcTable), srcIdx);
+                        break;
+                    }
+                } else if (srcValue == Value(ValueTraits::Redirect)) {
+                    // srcValue is already marked Redirect due to previous incomplete migration.
+                    TURF_TRACE(Grampa, 23, "[migrateRange] in-use cell already redirected", uptr(srcTable), srcIdx);
+                    break;
+                }
+                
+                // We've got a key/value pair to migrate.
+                // Reserve a destination cell in dstTable.
+                TURF_ASSERT(srcHash != KeyTraits::NullHash);
+                TURF_ASSERT(srcValue != Value(ValueTraits::NullValue));
+                TURF_ASSERT(srcValue != Value(ValueTraits::Redirect));
+                ureg destLeafIndex = (srcHash >> safeShift) & dstLeafMask;
+                Table* dstLeaf = dstLeafs[destLeafIndex];
+                Cell* dstCell;
+                ureg overflowIdx;
+                InsertResult result = insert(srcHash, dstLeaf, dstLeaf->sizeMask, dstCell, overflowIdx);
+                // During migration, a hash can only exist in one place among all the source tables,
+                // and it is only migrated by one thread. Therefore, the hash will never already exist
+                // in the destination table:
+                TURF_ASSERT(result != InsertResult_AlreadyFound);
+                if (result == InsertResult_Overflow) {
+                    // Destination overflow.
+                    // This can happen for several reasons. For example, the source table could have
+                    // existed of all deleted cells when it overflowed, resulting in a small destination
+                    // table size, but then another thread could re-insert all the same hashes
+                    // before the migration completed.
+                    // Caller will cancel the current migration and begin a new one.
+                    return destLeafIndex;
+                }
+                // Migrate the old value to the new cell.
+                for (;;) {
+                    // Copy srcValue to the destination.
+                    dstCell->value.store(srcValue, turf::Relaxed);
+                    // Try to place a Redirect marker in srcValue.
+                    Value doubleCheckedSrcValue = srcCell->value.compareExchange(srcValue, Value(ValueTraits::Redirect), turf::Relaxed);
+                    TURF_ASSERT(doubleCheckedSrcValue != Value(ValueTraits::Redirect)); // Only one thread can redirect a cell at a time.
+                    if (doubleCheckedSrcValue == srcValue) {
+                        // No racing writes to the src. We've successfully placed the Redirect marker.
+                        // srcValue was non-NULL when we decided to migrate it, but it may have changed to NULL
+                        // by a late-arriving erase.
+                        if (srcValue == Value(ValueTraits::NullValue))
+                            TURF_TRACE(Grampa, 24, "[migrateRange] racing update was erase", uptr(srcTable), srcIdx);
+                        break;
+                    }
+                    // There was a late-arriving write (or erase) to the src. Migrate the new value and try again.
+                    TURF_TRACE(Grampa, 25, "[migrateRange] race to update migrated value", uptr(srcTable), srcIdx);
+                    srcValue = doubleCheckedSrcValue;
+                }
+                // Cell successfully migrated. Proceed to next source cell.
+                break;
+            }
+        }
+    }
+    // Range has been migrated successfully.
+    return -1;
+}
+
+template <class Map>
+void Grampa<Map>::TableMigration::run() {
+    // Conditionally increment the shared # of workers.
+    ureg probeStatus = m_workerStatus.load(turf::Relaxed);
+    do {
+        if (probeStatus & 1) {
+            // End flag is already set, so do nothing.
+            TURF_TRACE(Grampa, 26, "[TableMigration::run] already ended", uptr(this), 0);
+            return;
+        }
+    } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, turf::Relaxed, turf::Relaxed));
+    // # of workers has been incremented, and the end flag is clear.
+    TURF_ASSERT((probeStatus & 1) == 0);
+
+    // Iterate over all source tables.
+    Source* sources = getSources();
+    for (ureg s = 0; s < m_numSources; s++) {
+        Source& source = sources[s];
+        // Loop over all migration units in this source table.
+        for (;;) {
+            if (m_workerStatus.load(turf::Relaxed) & 1) {
+                TURF_TRACE(Grampa, 27, "[TableMigration::run] detected end flag set", uptr(this), 0);
+                goto endMigration;
+            }
+            ureg startIdx = source.sourceIndex.fetchAdd(TableMigrationUnitSize, turf::Relaxed);
+            if (startIdx >= source.table->sizeMask + 1)
+                break;   // No more migration units in this table. Try next source table.
+            sreg overflowTableIndex = migrateRange(source.table, startIdx);
+            if  (overflowTableIndex >= 0) {
+                // *** FAILED MIGRATION ***
+                // TableMigration failed due to destination table overflow.
+                // No other thread can declare the migration successful at this point, because *this* unit will never complete, hence m_unitsRemaining won't reach zero.
+                // However, multiple threads can independently detect a failed migration at the same time.
+                TURF_TRACE(Grampa, 28, "[TableMigration::run] destination overflow", uptr(source.table), uptr(startIdx));
+                // The reason we store overflowTableIndex in a shared variable is because we must flush all the worker threads before
+                // we can safely deal with the overflow. Therefore, the thread that detects the failure is often different from the thread
+                // that deals with it.
+                // Store overflowTableIndex unconditionally; racing writes should be rare, and it doesn't matter which one wins.
+                sreg oldIndex = m_overflowTableIndex.exchange(overflowTableIndex, turf::Relaxed);
+                if (oldIndex >= 0)
+                    TURF_TRACE(Grampa, 29, "[TableMigration::run] race to set m_overflowTableIndex", uptr(overflowTableIndex), uptr(oldIndex));
+                m_workerStatus.fetchOr(1, turf::Relaxed);
+                goto endMigration;
+            }
+            sreg prevRemaining = m_unitsRemaining.fetchSub(1, turf::Relaxed);
+            TURF_ASSERT(prevRemaining > 0);
+            if (prevRemaining == 1) {
+                // *** SUCCESSFUL MIGRATION ***
+                // That was the last chunk to migrate.
+                m_workerStatus.fetchOr(1, turf::Relaxed);
+                goto endMigration;
+            }
+        }
+    }
+    TURF_TRACE(Grampa, 30, "[TableMigration::run] out of migration units", uptr(this), 0);
+
+endMigration:
+    // Decrement the shared # of workers.
+    probeStatus = m_workerStatus.fetchSub(2, turf::AcquireRelease);  // Ensure all modifications are visible to the thread that will publish
+    if (probeStatus >= 4) {
+        // There are other workers remaining. Return here so that only the very last worker will proceed.
+        TURF_TRACE(Grampa, 31, "[TableMigration::run] not the last worker", uptr(this), uptr(probeStatus));
+        return;
+    }
+
+    // We're the very last worker thread.
+    // Perform the appropriate post-migration step depending on whether the migration succeeded or failed.
+    TURF_ASSERT(probeStatus == 3);
+    sreg overflowTableIndex = m_overflowTableIndex.loadNonatomic();  // No racing writes at this point
+    if (overflowTableIndex < 0) {
+        // The migration succeeded. This is the most likely outcome. Publish the new subtree.
+        m_map.publishTableMigration(this);
+        // End the jobCoodinator.
+        sources[0].table->jobCoordinator.end();
+    } else {
+        // The migration failed due to the overflow of a destination table.
+        Table* origTable = sources[0].table;
+        ureg count = ureg(1) << (origTable->unsafeRangeShift - getUnsafeShift());
+        ureg lo = overflowTableIndex & ~(count - 1);
+        TURF_ASSERT(lo + count <= m_numDestinations);
+        turf::LockGuard<junction::striped::Mutex> guard(origTable->mutex);
+        SimpleJobCoordinator::Job* checkedJob = origTable->jobCoordinator.loadConsume();
+        if (checkedJob != this) {
+            TURF_TRACE(Grampa, 32, "[TableMigration::run] a new TableMigration was already started", uptr(origTable), uptr(checkedJob));
+        } else {
+            TableMigration* migration;
+            Table* overflowedTable = getDestinations()[overflowTableIndex];
+            if (overflowedTable->sizeMask + 1 < LeafSize) {
+                // The entire map is contained in a small table.
+                TURF_TRACE(Grampa, 33, "[TableMigration::run] overflow occured in a small map", uptr(origTable), uptr(checkedJob));
+                TURF_ASSERT(overflowedTable->unsafeRangeShift == sizeof(Hash) * 8);
+                TURF_ASSERT(overflowedTable->baseHash == 0);
+                TURF_ASSERT(m_numDestinations == 1);
+                TURF_ASSERT(m_baseHash == 0);
+                migration = TableMigration::create(m_map, m_numSources + 1, 1);
+                migration->m_baseHash = 0;
+                migration->m_safeShift = 0;
+                // Double the destination table size.
+                migration->getDestinations()[0] = Table::create((overflowedTable->sizeMask + 1) * 2, overflowedTable->baseHash, overflowedTable->unsafeRangeShift);
+            } else {
+                // The overflowed table is already the size of a leaf. Split it into two ranges.
+                if (count == 1) {
+                    TURF_TRACE(Grampa, 34, "[TableMigration::run] doubling subtree size after failure", uptr(origTable), uptr(checkedJob));
+                    migration = TableMigration::create(m_map, m_numSources + 1, m_numDestinations * 2);
+                    migration->m_baseHash = m_baseHash;
+                    migration->m_safeShift = getUnsafeShift() - 1;
+                    for (ureg i = 0; i < m_numDestinations; i++) {
+                        migration->getDestinations()[i * 2] = getDestinations()[i];
+                        migration->getDestinations()[i * 2 + 1] = getDestinations()[i];
+                    }
+                    count = 2;
+                } else {
+                    TURF_TRACE(Grampa, 35, "[TableMigration::run] keeping same subtree size after failure", uptr(origTable), uptr(checkedJob));
+                    migration = TableMigration::create(m_map, m_numSources + 1, m_numDestinations);
+                    migration->m_baseHash = m_baseHash;
+                    migration->m_safeShift = m_safeShift;
+                    memcpy(migration->getDestinations(), getDestinations(), m_numDestinations * sizeof(Table*));
+                }
+                Table* splitTable1 = Table::create(LeafSize, origTable->baseHash, origTable->unsafeRangeShift - 1);
+                ureg i = 0;
+                for (; i < count / 2; i++) {
+                    migration->getDestinations()[lo + i] = splitTable1;
+                }
+                ureg halfNumHashes = ureg(1) << (origTable->unsafeRangeShift - 1);
+                Table* splitTable2 = Table::create(LeafSize, origTable->baseHash + halfNumHashes, origTable->unsafeRangeShift - 1);
+                for (; i < count; i++) {
+                    migration->getDestinations()[lo + i] = splitTable2;
+                }
+            }
+            // Transfer source tables to the new migration.
+            for (ureg i = 0; i < m_numSources; i++) {
+                migration->getSources()[i].table = getSources()[i].table;
+                migration->getSources()[i].sourceIndex.storeNonatomic(0);
+                getSources()[i].table = NULL;
+            }
+            migration->getSources()[m_numSources].table = overflowedTable;
+            migration->getSources()[m_numSources].sourceIndex.storeNonatomic(0);
+            // Calculate total number of migration units to move.
+            ureg unitsRemaining = 0;
+            for (ureg s = 0; s < migration->m_numSources; s++)
+                unitsRemaining += migration->getSources()[s].table->getNumMigrationUnits();
+            migration->m_unitsRemaining.storeNonatomic(unitsRemaining);
+            // Publish the new migration.
+            origTable->jobCoordinator.storeRelease(migration);
+        }
+    }
+
+    // We're done with this TableMigration. Queue it for GC.
+    DefaultQSBR.enqueue(&TableMigration::destroy, this);
+}
+
+template<class Map>
+void Grampa<Map>::FlatTreeMigration::run() {
+    // Conditionally increment the shared # of workers.
+    ureg probeStatus = m_workerStatus.load(turf::Relaxed);
+    do {
+        if (probeStatus & 1) {
+            // End flag is already set, so do nothing.
+            TURF_TRACE(Grampa, 36, "[FlatTreeMigration::run] already ended", uptr(this), 0);
+            return;
+        }
+    } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, turf::Relaxed, turf::Relaxed));
+    // # of workers has been incremented, and the end flag is clear.
+    TURF_ASSERT((probeStatus & 1) == 0);
+
+    // Loop over all migration units
+    ureg srcSize = (Hash(-1) >> m_source->safeShift) + 1;
+    // FIXME: Support migration to smaller flattrees
+    TURF_ASSERT(m_destination->safeShift < m_source->safeShift);
+    ureg repeat = ureg(1) << (m_source->safeShift - m_destination->safeShift);
+    for (;;) {
+        ureg srcStart = m_sourceIndex.fetchAdd(FlatTreeMigrationUnitSize, turf::Relaxed);
+        if (srcStart >= srcSize)
+            break;      // No more migration units in this flattree.
+        // Migrate this range
+        ureg srcEnd = turf::util::min(srcSize, srcStart + FlatTreeMigrationUnitSize);
+        ureg dst = srcStart * repeat;
+        for (ureg src = srcStart; src < srcEnd; src++) {
+            // Pointers in the source table can be changed at any time due to concurrent subtree publishing,
+            // so we need to exchange them with Redirect markers.
+            Table* t = m_source->getTables()[src].exchange((Table*) RedirectFlatTree, turf::Relaxed);
+            TURF_ASSERT(uptr(t) != RedirectFlatTree);
+            for (ureg r = repeat; r > 0; r--) {
+                m_destination->getTables()[dst].storeNonatomic(t);
+                dst++;
+            }
+        }
+        // Decrement m_unitsRemaining
+        sreg prevRemaining = m_unitsRemaining.fetchSub(1, turf::Relaxed);
+        if (prevRemaining == 1) {
+            // *** SUCCESSFUL MIGRATION ***
+            // That was the last chunk to migrate.
+            m_workerStatus.fetchOr(1, turf::Relaxed);
+            break;
+        }
+    }
+
+    // Decrement the shared # of workers.
+    probeStatus = m_workerStatus.fetchSub(2, turf::AcquireRelease);    // AcquireRelease makes all previous writes visible to the last worker thread.
+    if (probeStatus >= 4) {
+        // There are other workers remaining. Return here so that only the very last worker will proceed.
+        return;
+    }
+
+    // We're the very last worker thread.
+    // Publish the new flattree.
+    TURF_ASSERT(probeStatus == 3);      // End flag must be set
+    m_map.publishFlatTreeMigration(this);
+    m_completed.signal();
+
+    // We're done with this FlatTreeMigration. Queue it for GC.
+    DefaultQSBR.enqueue(&FlatTreeMigration::destroy, this);
+}
+
+} // namespace details
+} // namespace junction
+
+#endif // JUNCTION_DETAILS_GRAMPA_H
diff --git a/junction/details/LeapFrog.cpp b/junction/details/LeapFrog.cpp
new file mode 100644 (file)
index 0000000..3a7011e
--- /dev/null
@@ -0,0 +1,57 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <junction/details/LeapFrog.h>
+#include <turf/Heap.h>
+
+namespace junction {
+namespace details {
+
+TURF_TRACE_DEFINE_BEGIN(LeapFrog, 33) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[find] called")
+TURF_TRACE_DEFINE("[find] found existing cell optimistically")
+TURF_TRACE_DEFINE("[find] found existing cell")
+TURF_TRACE_DEFINE("[insert] called")
+TURF_TRACE_DEFINE("[insert] reserved first cell")
+TURF_TRACE_DEFINE("[insert] race to reserve first cell")
+TURF_TRACE_DEFINE("[insert] found in first cell")
+TURF_TRACE_DEFINE("[insert] race to read hash")
+TURF_TRACE_DEFINE("[insert] found in probe chain")
+TURF_TRACE_DEFINE("[insert] reserved cell")
+TURF_TRACE_DEFINE("[insert] race to reserve cell")
+TURF_TRACE_DEFINE("[insert] found outside probe chain")
+TURF_TRACE_DEFINE("[insert] found late-arriving cell in same bucket")
+TURF_TRACE_DEFINE("[insert] set link on behalf of late-arriving cell")
+TURF_TRACE_DEFINE("[insert] overflow")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] called")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] new migration already exists")
+TURF_TRACE_DEFINE("[beginTableMigrationToSize] new migration already exists (double-checked)")
+TURF_TRACE_DEFINE("[beginTableMigration] redirected while determining table size")
+TURF_TRACE_DEFINE("[migrateRange] empty cell already redirected")
+TURF_TRACE_DEFINE("[migrateRange] race to insert key")
+TURF_TRACE_DEFINE("[migrateRange] race to insert value")
+TURF_TRACE_DEFINE("[migrateRange] race inserted Redirect")
+TURF_TRACE_DEFINE("[migrateRange] in-use cell already redirected")
+TURF_TRACE_DEFINE("[migrateRange] racing update was erase")
+TURF_TRACE_DEFINE("[migrateRange] race to update migrated value")
+TURF_TRACE_DEFINE("[TableMigration::run] already ended")
+TURF_TRACE_DEFINE("[TableMigration::run] detected end flag set")
+TURF_TRACE_DEFINE("[TableMigration::run] destination overflow")
+TURF_TRACE_DEFINE("[TableMigration::run] race to set m_overflowed")
+TURF_TRACE_DEFINE("[TableMigration::run] out of migration units")
+TURF_TRACE_DEFINE("[TableMigration::run] not the last worker")
+TURF_TRACE_DEFINE("[TableMigration::run] a new TableMigration was already started")
+TURF_TRACE_DEFINE_END(LeapFrog, 33)
+
+} // namespace details
+} // namespace junction
diff --git a/junction/details/LeapFrog.h b/junction/details/LeapFrog.h
new file mode 100644 (file)
index 0000000..7b1e395
--- /dev/null
@@ -0,0 +1,561 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_DETAILS_LEAPFROG_H
+#define JUNCTION_DETAILS_LEAPFROG_H
+
+#include <junction/Core.h>
+#include <turf/Atomic.h>
+#include <turf/Mutex.h>
+#include <turf/ManualResetEvent.h>
+#include <turf/Util.h>
+#include <junction/MapTraits.h>
+#include <turf/Trace.h>
+#include <turf/Heap.h>
+#include <junction/SimpleJobCoordinator.h>
+#include <junction/QSBR.h>
+
+namespace junction {
+namespace details {
+
+TURF_TRACE_DECLARE(LeapFrog, 33)
+
+template<class Map>
+struct LeapFrog {
+    typedef typename Map::Hash Hash;
+    typedef typename Map::Value Value;
+    typedef typename Map::KeyTraits KeyTraits;
+    typedef typename Map::ValueTraits ValueTraits;
+
+    static const ureg InitialSize = 8;
+    static const ureg TableMigrationUnitSize = 32;
+    static const ureg LinearSearchLimit = 128;
+    static const ureg CellsInUseSample = LinearSearchLimit;
+    TURF_STATIC_ASSERT(LinearSearchLimit > 0 && LinearSearchLimit < 256); // Must fit in CellGroup::links
+    TURF_STATIC_ASSERT(CellsInUseSample > 0 && CellsInUseSample <= LinearSearchLimit); // Limit sample to failed search chain
+
+    struct Cell {
+        turf::Atomic<Hash> hash;
+        turf::Atomic<Value> value;
+    };
+
+    struct CellGroup {
+        // Every cell in the table actually represents a bucket of cells, all linked together in a probe chain.
+        // Each cell in the probe chain is located within the table itself.
+        // "deltas" determines the index of the next cell in the probe chain.
+        // The first cell in the chain is the one that was hashed. It may or may not actually belong in the bucket.
+        // The "second" cell in the chain is given by deltas 0 - 3. It's guaranteed to belong in the bucket.
+        // All subsequent cells in the chain is given by deltas 4 - 7. Also guaranteed to belong in the bucket.
+        turf::Atomic<u8> deltas[8];
+        Cell cells[4];
+    };
+
+    struct Table {
+        const ureg sizeMask;                    // a power of two minus one
+        turf::Mutex mutex;                      // to DCLI the TableMigration (stored in the jobCoordinator)
+        SimpleJobCoordinator jobCoordinator;    // makes all blocked threads participate in the migration
+
+        Table(ureg sizeMask) : sizeMask(sizeMask) {
+        }
+
+        static Table* create(ureg tableSize) {
+            TURF_ASSERT(turf::util::isPowerOf2(tableSize));
+            TURF_ASSERT(tableSize >= 4);
+            ureg numGroups = tableSize >> 2;
+            Table* table = (Table*) TURF_HEAP.alloc(sizeof(Table) + sizeof(CellGroup) * numGroups);
+            new(table) Table(tableSize - 1);
+            for (ureg i = 0; i < numGroups; i++) {
+                CellGroup* group = table->getCellGroups() + i;
+                for (ureg j = 0; j < 4; j++) {
+                    group->deltas[j].storeNonatomic(0);
+                    group->deltas[j + 4].storeNonatomic(0);
+                    group->cells[j].hash.storeNonatomic(KeyTraits::NullHash);
+                    group->cells[j].value.storeNonatomic(Value(ValueTraits::NullValue));
+                }
+            }
+            return table;
+        }
+
+        void destroy() {
+            this->Table::~Table();
+            TURF_HEAP.free(this);
+        }
+
+        CellGroup* getCellGroups() const {
+            return (CellGroup*) (this + 1);
+        }
+
+        ureg getNumMigrationUnits() const {
+            return sizeMask / TableMigrationUnitSize + 1;
+        }
+    };
+
+    class TableMigration : public SimpleJobCoordinator::Job {
+    public:
+        struct Source {
+            Table* table;
+            turf::Atomic<ureg> sourceIndex;
+        };
+
+        Map& m_map;
+        Table* m_destination;
+        turf::Atomic<ureg> m_workerStatus;          // number of workers + end flag
+        turf::Atomic<bool> m_overflowed;
+        turf::Atomic<sreg> m_unitsRemaining;
+        ureg m_numSources;
+
+        TableMigration(Map& map) : m_map(map) {
+        }
+
+        static TableMigration* create(Map& map, ureg numSources) {
+            TableMigration* migration = (TableMigration*) TURF_HEAP.alloc(sizeof(TableMigration) + sizeof(TableMigration::Source) * numSources);
+            new(migration) TableMigration(map);
+            migration->m_workerStatus.storeNonatomic(0);
+            migration->m_overflowed.storeNonatomic(false);
+            migration->m_unitsRemaining.storeNonatomic(0);
+            migration->m_numSources = numSources;
+            // Caller is responsible for filling in sources & destination
+            return migration;
+        }
+
+        virtual ~TableMigration() TURF_OVERRIDE {
+        }
+
+        void destroy() {
+            // Destroy all source tables.
+            for (ureg i = 0; i < m_numSources; i++)
+                if (getSources()[i].table)
+                    getSources()[i].table->destroy();
+            // Delete the migration object itself.
+            this->TableMigration::~TableMigration();
+            TURF_HEAP.free(this);
+        }
+
+        Source* getSources() const {
+            return (Source*) (this + 1);
+        }
+
+        bool migrateRange(Table* srcTable, ureg startIdx);
+        virtual void run() TURF_OVERRIDE;
+    };
+
+    static Cell* find(Hash hash, Table* table) {
+        TURF_TRACE(LeapFrog, 0, "[find] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        ureg sizeMask = table->sizeMask;
+        // Optimistically check hashed cell even though it might belong to another bucket
+        ureg idx = hash & sizeMask;
+        CellGroup* group = table->getCellGroups() + (idx >> 2);
+        Cell* cell = group->cells + (idx & 3);
+        Hash probeHash = cell->hash.load(turf::Relaxed);
+        if (probeHash == hash) {
+            TURF_TRACE(LeapFrog, 1, "[find] found existing cell optimistically", uptr(table), idx);
+            return cell;
+        } else if (probeHash == KeyTraits::NullHash) {
+            return cell = NULL;
+        }
+        // Follow probe chain for our bucket
+        u8 delta = group->deltas[idx & 3].load(turf::Relaxed);
+        while (delta) {
+            idx = (idx + delta) & sizeMask;
+            group = table->getCellGroups() + (idx >> 2);
+            cell = group->cells + (idx & 3);
+            Hash probeHash = cell->hash.load(turf::Relaxed);
+            // Note: probeHash might actually be NULL due to memory reordering of a concurrent insert,
+            // but we don't check for it. We just follow the probe chain.
+            if (probeHash == hash) {
+                TURF_TRACE(LeapFrog, 2, "[find] found existing cell", uptr(table), idx);
+                return cell;
+            }
+            delta = group->deltas[(idx & 3) + 4].load(turf::Relaxed);
+        }
+        // End of probe chain, not found
+        return NULL;
+    }
+
+    // FIXME: Possible optimization: Dedicated insert for migration? It wouldn't check for InsertResult_AlreadyFound.
+    enum InsertResult {
+        InsertResult_AlreadyFound,
+        InsertResult_InsertedNew,
+        InsertResult_Overflow
+    };
+    static InsertResult insert(Hash hash, Table* table, Cell*& cell, ureg& overflowIdx) {
+        TURF_TRACE(LeapFrog, 3, "[insert] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        ureg sizeMask = table->sizeMask;
+        ureg idx = hash;
+
+        // Check hashed cell first, though it may not even belong to the bucket.
+        CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+        cell = group->cells + (idx & 3);
+        Hash probeHash = cell->hash.load(turf::Relaxed);
+        if (probeHash == KeyTraits::NullHash) {
+            if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
+                TURF_TRACE(LeapFrog, 4, "[insert] reserved first cell", uptr(table), idx);
+                // There are no links to set. We're done.
+                return InsertResult_InsertedNew;
+            } else {
+                TURF_TRACE(LeapFrog, 5, "[insert] race to reserve first cell", uptr(table), idx);
+                // Fall through to check if it was the same hash...
+            }
+        }
+        if (probeHash == hash) {
+            TURF_TRACE(LeapFrog, 6, "[insert] found in first cell", uptr(table), idx);
+            return InsertResult_AlreadyFound;
+        }
+
+        // Follow the link chain for this bucket.
+        ureg maxIdx = idx + sizeMask;
+        ureg linkLevel = 0;
+        turf::Atomic<u8>* prevLink;
+        for (;;) {
+        followLink:
+            prevLink = group->deltas + ((idx & 3) + linkLevel);
+            linkLevel = 4;
+            u8 probeDelta = prevLink->load(turf::Relaxed);
+            if (probeDelta) {
+                idx += probeDelta;
+                // Check the hash for this cell.
+                group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+                cell = group->cells + (idx & 3);
+                probeHash = cell->hash.load(turf::Relaxed);
+                if (probeHash == KeyTraits::NullHash) {
+                    // Cell was linked, but hash is not visible yet.
+                    // We could avoid this case (and guarantee it's visible) using acquire & release, but instead,
+                    // just poll until it becomes visible.
+                    TURF_TRACE(LeapFrog, 7, "[insert] race to read hash", uptr(table), idx);
+                    do {
+                        probeHash = cell->hash.load(turf::Acquire);
+                    } while (probeHash == KeyTraits::NullHash);
+                }
+                TURF_ASSERT(((probeHash ^ hash) & sizeMask) == 0);   // Only hashes in same bucket can be linked
+                if (probeHash == hash) {
+                    TURF_TRACE(LeapFrog, 8, "[insert] found in probe chain", uptr(table), idx);
+                    return InsertResult_AlreadyFound;
+                }
+            } else {
+                // Reached the end of the link chain for this bucket.
+                // Switch to linear probing until we reserve a new cell or find a late-arriving cell in the same bucket.
+                ureg prevLinkIdx = idx;
+                TURF_ASSERT(sreg(maxIdx - idx) >= 0);    // Nobody would have linked an idx that's out of range.
+                ureg linearProbesRemaining = turf::util::min(maxIdx - idx, LinearSearchLimit);
+                while (linearProbesRemaining-- > 0) {
+                    idx++;
+                    group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+                    cell = group->cells + (idx & 3);
+                    probeHash = cell->hash.load(turf::Relaxed);
+                    if (probeHash == KeyTraits::NullHash) {
+                        // It's an empty cell. Try to reserve it.
+                        if (cell->hash.compareExchangeStrong(probeHash, hash, turf::Relaxed)) {
+                            // Success. We've reserved the cell. Link it to previous cell in same bucket.
+                            TURF_TRACE(LeapFrog, 9, "[insert] reserved cell", uptr(table), idx);
+                            TURF_ASSERT(probeDelta == 0);
+                            u8 desiredDelta = idx - prevLinkIdx;
+#if TURF_WITH_ASSERTS                            
+                            probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
+                            TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
+#else
+                            prevLink->store(desiredDelta, turf::Relaxed);
+#endif
+                            return InsertResult_InsertedNew;
+                        } else {
+                            TURF_TRACE(LeapFrog, 10, "[insert] race to reserve cell", uptr(table), idx);
+                            // Fall through to check if it's the same hash...
+                        }
+                    }
+                    Hash x = (probeHash ^ hash);
+                    // Check for same hash.
+                    if (!x) {
+                        TURF_TRACE(LeapFrog, 11, "[insert] found outside probe chain", uptr(table), idx);
+                        return InsertResult_AlreadyFound;
+                    }
+                    // Check for same bucket.
+                    if ((x & sizeMask) == 0) {
+                        TURF_TRACE(LeapFrog, 12, "[insert] found late-arriving cell in same bucket", uptr(table), idx);
+                        // Attempt to set the link on behalf of the late-arriving cell.
+                        // This is usually redundant, but if we don't attempt to set the late-arriving cell's link here,
+                        // there's no guarantee that our own link chain will be well-formed by the time this function returns.
+                        // (Indeed, subsequent lookups sometimes failed during testing, for this exact reason.)
+                        u8 desiredDelta = idx - prevLinkIdx;
+#if TURF_WITH_ASSERTS                            
+                        probeDelta = prevLink->exchange(desiredDelta, turf::Relaxed);
+                        TURF_ASSERT(probeDelta == 0 || probeDelta == desiredDelta);
+                        if (probeDelta == 0)
+                            TURF_TRACE(LeapFrog, 13, "[insert] set link on behalf of late-arriving cell", uptr(table), idx);
+#else
+                        prevLink->store(desiredDelta, turf::Relaxed);
+#endif                    
+                        goto followLink;  // Try to follow link chain for the bucket again.
+                    }
+                    // Continue linear search...
+                }
+                // Table is too full to insert.
+                overflowIdx = idx + 1;
+                TURF_TRACE(LeapFrog, 14, "[insert] overflow", uptr(table), overflowIdx);
+                return InsertResult_Overflow;
+            }
+        }
+    }
+
+    static void beginTableMigrationToSize(Map& map, Table* table, ureg nextTableSize) {
+        // Create new migration by DCLI.
+        TURF_TRACE(LeapFrog, 15, "[beginTableMigrationToSize] called", 0, 0);
+        SimpleJobCoordinator::Job* job = table->jobCoordinator.loadConsume();
+        if (job) {
+            TURF_TRACE(LeapFrog, 16, "[beginTableMigrationToSize] new migration already exists", 0, 0);
+        } else {
+            turf::LockGuard<turf::Mutex> guard(table->mutex);
+            job = table->jobCoordinator.loadConsume();  // Non-atomic would be sufficient, but that's OK.
+            if (job) {
+                TURF_TRACE(LeapFrog, 17, "[beginTableMigrationToSize] new migration already exists (double-checked)", 0, 0);
+            } else {
+                // Create new migration.
+                TableMigration* migration = TableMigration::create(map, 1);
+                migration->m_unitsRemaining.storeNonatomic(table->getNumMigrationUnits());
+                migration->getSources()[0].table = table;
+                migration->getSources()[0].sourceIndex.storeNonatomic(0);
+                migration->m_destination = Table::create(nextTableSize);
+                // Publish the new migration.
+                table->jobCoordinator.storeRelease(migration);
+            }
+        }
+    }
+
+    static void beginTableMigration(Map& map, Table* table, ureg overflowIdx) {
+        // Estimate number of cells in use based on a small sample.
+        ureg sizeMask = table->sizeMask;
+        ureg idx = overflowIdx - CellsInUseSample;
+        ureg inUseCells = 0;
+        for (ureg linearProbesRemaining = CellsInUseSample; linearProbesRemaining > 0; linearProbesRemaining--) {
+            CellGroup* group = table->getCellGroups() + ((idx & sizeMask) >> 2);
+            Cell* cell = group->cells + (idx & 3);
+            Value value = cell->value.load(turf::Relaxed);
+            if (value == Value(ValueTraits::Redirect)) {
+                // Another thread kicked off the jobCoordinator. The caller will participate upon return.
+                TURF_TRACE(LeapFrog, 18, "[beginTableMigration] redirected while determining table size", 0, 0);
+                return;
+            }
+            if (value != Value(ValueTraits::NullValue))
+                inUseCells++;
+            idx++;
+        }
+        float inUseRatio = float(inUseCells) / CellsInUseSample;
+        float estimatedInUse = (sizeMask + 1) * inUseRatio;
+        ureg nextTableSize = turf::util::roundUpPowerOf2(ureg(estimatedInUse * 2));
+        beginTableMigrationToSize(map, table, nextTableSize);
+    }
+}; // LeapFrog
+
+template<class Map>
+bool LeapFrog<Map>::TableMigration::migrateRange(Table* srcTable, ureg startIdx) {
+    ureg srcSizeMask = srcTable->sizeMask;
+    ureg endIdx = turf::util::min(startIdx + TableMigrationUnitSize, srcSizeMask + 1);
+    // Iterate over source range.
+    for (ureg srcIdx = startIdx; srcIdx < endIdx; srcIdx++) {
+        CellGroup* srcGroup = srcTable->getCellGroups() + ((srcIdx & srcSizeMask) >> 2);
+        Cell* srcCell = srcGroup->cells + (srcIdx & 3);
+        Hash srcHash;
+        Value srcValue;
+        // Fetch the srcHash and srcValue.
+        for (;;) {
+            srcHash = srcCell->hash.load(turf::Relaxed);
+            if (srcHash == KeyTraits::NullHash) {
+                // An unused cell. Try to put a Redirect marker in its value.
+                srcValue = srcCell->value.compareExchange(Value(ValueTraits::NullValue), Value(ValueTraits::Redirect), turf::Relaxed);
+                if (srcValue == Value(ValueTraits::Redirect)) {
+                    // srcValue is already marked Redirect due to previous incomplete migration.
+                    TURF_TRACE(LeapFrog, 19, "[migrateRange] empty cell already redirected", uptr(srcTable), srcIdx);
+                    break;
+                }
+                if (srcValue == Value(ValueTraits::NullValue))
+                    break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                TURF_TRACE(LeapFrog, 20, "[migrateRange] race to insert key", uptr(srcTable), srcIdx);
+                // Otherwise, somebody just claimed the cell. Read srcHash again...
+            } else {
+                // Check for deleted/uninitialized value.
+                srcValue = srcCell->value.load(turf::Relaxed);
+                if (srcValue == Value(ValueTraits::NullValue)) {
+                    // Try to put a Redirect marker.
+                    if (srcCell->value.compareExchangeStrong(srcValue, Value(ValueTraits::Redirect), turf::Relaxed))
+                        break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                    TURF_TRACE(LeapFrog, 21, "[migrateRange] race to insert value", uptr(srcTable), srcIdx);
+                    if (srcValue == Value(ValueTraits::Redirect)) {
+                        // FIXME: I don't think this will happen. Investigate & change to assert
+                        TURF_TRACE(LeapFrog, 22, "[migrateRange] race inserted Redirect", uptr(srcTable), srcIdx);
+                        break;
+                    }
+                } else if (srcValue == Value(ValueTraits::Redirect)) {
+                    // srcValue is already marked Redirect due to previous incomplete migration.
+                    TURF_TRACE(LeapFrog, 23, "[migrateRange] in-use cell already redirected", uptr(srcTable), srcIdx);
+                    break;
+                }
+                
+                // We've got a key/value pair to migrate.
+                // Reserve a destination cell in the destination.
+                TURF_ASSERT(srcHash != KeyTraits::NullHash);
+                TURF_ASSERT(srcValue != Value(ValueTraits::NullValue));
+                TURF_ASSERT(srcValue != Value(ValueTraits::Redirect));
+                Cell* dstCell;
+                ureg overflowIdx;
+                InsertResult result = insert(srcHash, m_destination, dstCell, overflowIdx);
+                // During migration, a hash can only exist in one place among all the source tables,
+                // and it is only migrated by one thread. Therefore, the hash will never already exist
+                // in the destination table:
+                TURF_ASSERT(result != InsertResult_AlreadyFound);
+                if (result == InsertResult_Overflow) {
+                    // Destination overflow.
+                    // This can happen for several reasons. For example, the source table could have
+                    // existed of all deleted cells when it overflowed, resulting in a small destination
+                    // table size, but then another thread could re-insert all the same hashes
+                    // before the migration completed.
+                    // Caller will cancel the current migration and begin a new one.
+                    return false;
+                }
+                // Migrate the old value to the new cell.
+                for (;;) {
+                    // Copy srcValue to the destination.
+                    dstCell->value.store(srcValue, turf::Relaxed);
+                    // Try to place a Redirect marker in srcValue.
+                    Value doubleCheckedSrcValue = srcCell->value.compareExchange(srcValue, Value(ValueTraits::Redirect), turf::Relaxed);
+                    TURF_ASSERT(doubleCheckedSrcValue != Value(ValueTraits::Redirect)); // Only one thread can redirect a cell at a time.
+                    if (doubleCheckedSrcValue == srcValue) {
+                        // No racing writes to the src. We've successfully placed the Redirect marker.
+                        // srcValue was non-NULL when we decided to migrate it, but it may have changed to NULL
+                        // by a late-arriving erase.
+                        if (srcValue == Value(ValueTraits::NullValue))
+                            TURF_TRACE(LeapFrog, 24, "[migrateRange] racing update was erase", uptr(srcTable), srcIdx);
+                        break;
+                    }
+                    // There was a late-arriving write (or erase) to the src. Migrate the new value and try again.
+                    TURF_TRACE(LeapFrog, 25, "[migrateRange] race to update migrated value", uptr(srcTable), srcIdx);
+                    srcValue = doubleCheckedSrcValue;
+                }
+                // Cell successfully migrated. Proceed to next source cell.
+                break;
+            }
+        }
+    }
+    // Range has been migrated successfully.
+    return true;
+}
+
+template <class Map>
+void LeapFrog<Map>::TableMigration::run() {
+    // Conditionally increment the shared # of workers.
+    ureg probeStatus = m_workerStatus.load(turf::Relaxed);
+    do {
+        if (probeStatus & 1) {
+            // End flag is already set, so do nothing.
+            TURF_TRACE(LeapFrog, 26, "[TableMigration::run] already ended", uptr(this), 0);
+            return;
+        }
+    } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, turf::Relaxed, turf::Relaxed));
+    // # of workers has been incremented, and the end flag is clear.
+    TURF_ASSERT((probeStatus & 1) == 0);
+
+    // Iterate over all source tables.
+    for (ureg s = 0; s < m_numSources; s++) {
+        Source& source = getSources()[s];
+        // Loop over all migration units in this source table.
+        for (;;) {
+            if (m_workerStatus.load(turf::Relaxed) & 1) {
+                TURF_TRACE(LeapFrog, 27, "[TableMigration::run] detected end flag set", uptr(this), 0);
+                goto endMigration;
+            }
+            ureg startIdx = source.sourceIndex.fetchAdd(TableMigrationUnitSize, turf::Relaxed);
+            if (startIdx >= source.table->sizeMask + 1)
+                break;   // No more migration units in this table. Try next source table.
+            bool overflowed = !migrateRange(source.table, startIdx);
+            if (overflowed) {
+                // *** FAILED MIGRATION ***
+                // TableMigration failed due to destination table overflow.
+                // No other thread can declare the migration successful at this point, because *this* unit will never complete, hence m_unitsRemaining won't reach zero.
+                // However, multiple threads can independently detect a failed migration at the same time.
+                TURF_TRACE(LeapFrog, 28, "[TableMigration::run] destination overflow", uptr(source.table), uptr(startIdx));
+                // The reason we store overflowed in a shared variable is because we can must flush all the worker threads before
+                // we can safely deal with the overflow. Therefore, the thread that detects the failure is often different from the thread
+                // that deals with it.
+                bool oldOverflowed = m_overflowed.exchange(overflowed, turf::Relaxed);
+                if (oldOverflowed)
+                    TURF_TRACE(LeapFrog, 29, "[TableMigration::run] race to set m_overflowed", uptr(overflowed), uptr(oldOverflowed));
+                m_workerStatus.fetchOr(1, turf::Relaxed);
+                goto endMigration;
+            }
+            sreg prevRemaining = m_unitsRemaining.fetchSub(1, turf::Relaxed);
+            TURF_ASSERT(prevRemaining > 0);
+            if (prevRemaining == 1) {
+                // *** SUCCESSFUL MIGRATION ***
+                // That was the last chunk to migrate.
+                m_workerStatus.fetchOr(1, turf::Relaxed);
+                goto endMigration;
+            }
+        }
+    }
+    TURF_TRACE(LeapFrog, 30, "[TableMigration::run] out of migration units", uptr(this), 0);
+
+endMigration:
+    // Decrement the shared # of workers.
+    probeStatus = m_workerStatus.fetchSub(2, turf::AcquireRelease);    // AcquireRelease makes all previous writes visible to the last worker thread.
+    if (probeStatus >= 4) {
+        // There are other workers remaining. Return here so that only the very last worker will proceed.
+        TURF_TRACE(LeapFrog, 31, "[TableMigration::run] not the last worker", uptr(this), uptr(probeStatus));
+        return;
+    }
+
+    // We're the very last worker thread.
+    // Perform the appropriate post-migration step depending on whether the migration succeeded or failed.
+    TURF_ASSERT(probeStatus == 3);
+    bool overflowed = m_overflowed.loadNonatomic();  // No racing writes at this point
+    if (!overflowed) {
+        // The migration succeeded. This is the most likely outcome. Publish the new subtree.
+        m_map.publishTableMigration(this);
+        // End the jobCoodinator.
+        getSources()[0].table->jobCoordinator.end();
+    } else {
+        // The migration failed due to the overflow of the destination table.
+        Table* origTable = getSources()[0].table;
+        turf::LockGuard<turf::Mutex> guard(origTable->mutex);
+        SimpleJobCoordinator::Job* checkedJob = origTable->jobCoordinator.loadConsume();
+        if (checkedJob != this) {
+            TURF_TRACE(LeapFrog, 32, "[TableMigration::run] a new TableMigration was already started", uptr(origTable), uptr(checkedJob));
+        } else {
+            TableMigration* migration = TableMigration::create(m_map, m_numSources + 1);
+            // Double the destination table size.
+            migration->m_destination = Table::create((m_destination->sizeMask + 1) * 2);
+            // Transfer source tables to the new migration.
+            for (ureg i = 0; i < m_numSources; i++) {
+                migration->getSources()[i].table = getSources()[i].table;
+                getSources()[i].table = NULL;
+                migration->getSources()[i].sourceIndex.storeNonatomic(0);
+            }
+            migration->getSources()[m_numSources].table = m_destination;
+            migration->getSources()[m_numSources].sourceIndex.storeNonatomic(0);
+            // Calculate total number of migration units to move.
+            ureg unitsRemaining = 0;
+            for (ureg s = 0; s < migration->m_numSources; s++)
+                unitsRemaining += migration->getSources()[s].table->getNumMigrationUnits();
+            migration->m_unitsRemaining.storeNonatomic(unitsRemaining);
+            // Publish the new migration.
+            origTable->jobCoordinator.storeRelease(migration);
+        }
+    }
+
+    // We're done with this TableMigration. Queue it for GC.
+    DefaultQSBR.enqueue(&TableMigration::destroy, this);
+}
+
+} // namespace details
+} // namespace junction
+
+#endif // JUNCTION_DETAILS_LEAPFROG_H
diff --git a/junction/details/Linear.cpp b/junction/details/Linear.cpp
new file mode 100644 (file)
index 0000000..d731567
--- /dev/null
@@ -0,0 +1,46 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <junction/details/Linear.h>
+#include <turf/Heap.h>
+
+namespace junction {
+namespace details {
+
+TURF_TRACE_DEFINE_BEGIN(Linear, 22) // autogenerated by TidySource.py
+TURF_TRACE_DEFINE("[find] called")
+TURF_TRACE_DEFINE("[find] found existing cell")
+TURF_TRACE_DEFINE("[insert] called")
+TURF_TRACE_DEFINE("[insert] found existing cell")
+TURF_TRACE_DEFINE("[insert] ran out of cellsRemaining")
+TURF_TRACE_DEFINE("[insert] reserved cell")
+TURF_TRACE_DEFINE("[insert] detected race to reserve cell")
+TURF_TRACE_DEFINE("[insert] race reserved same hash")
+TURF_TRACE_DEFINE("[beginTableMigration] called")
+TURF_TRACE_DEFINE("[beginTableMigration] new migration already exists")
+TURF_TRACE_DEFINE("[beginTableMigration] new migration already exists (double-checked)")
+TURF_TRACE_DEFINE("[table] restarting valuesRemaining CAS loop")
+TURF_TRACE_DEFINE("[table] valuesRemaining CAS failed")
+TURF_TRACE_DEFINE("[migrateRange] empty cell already redirected")
+TURF_TRACE_DEFINE("[migrateRange] race to insert key")
+TURF_TRACE_DEFINE("[migrateRange] race to insert value")
+TURF_TRACE_DEFINE("[migrateRange] racing update was erase")
+TURF_TRACE_DEFINE("[migrateRange] race to update migrated value")
+TURF_TRACE_DEFINE("[TableMigration::run] already ended")
+TURF_TRACE_DEFINE("[TableMigration::run] detected end flag set")
+TURF_TRACE_DEFINE("[TableMigration::run] out of migration units")
+TURF_TRACE_DEFINE("[TableMigration::run] not the last worker")
+TURF_TRACE_DEFINE_END(Linear, 22)
+
+} // namespace details
+} // namespace junction
diff --git a/junction/details/Linear.h b/junction/details/Linear.h
new file mode 100644 (file)
index 0000000..f466cb0
--- /dev/null
@@ -0,0 +1,375 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_DETAILS_LINEAR_H
+#define JUNCTION_DETAILS_LINEAR_H
+
+#include <junction/Core.h>
+#include <turf/Atomic.h>
+#include <turf/Mutex.h>
+#include <turf/ManualResetEvent.h>
+#include <turf/Util.h>
+#include <junction/MapTraits.h>
+#include <turf/Trace.h>
+#include <turf/Heap.h>
+#include <junction/SimpleJobCoordinator.h>
+#include <junction/QSBR.h>
+
+namespace junction {
+namespace details {
+
+TURF_TRACE_DECLARE(Linear, 22)
+
+template<class Map>
+struct Linear {
+    typedef typename Map::Hash Hash;
+    typedef typename Map::Value Value;
+    typedef typename Map::KeyTraits KeyTraits;
+    typedef typename Map::ValueTraits ValueTraits;
+
+    static const ureg InitialSize = 8;
+    static const ureg TableMigrationUnitSize = 32;
+    static const ureg LinearSearchLimit = 128;
+    static const ureg CellsInUseSample = LinearSearchLimit;
+    TURF_STATIC_ASSERT(LinearSearchLimit > 0 && LinearSearchLimit < 256); // Must fit in CellGroup::links
+    TURF_STATIC_ASSERT(CellsInUseSample > 0 && CellsInUseSample <= LinearSearchLimit); // Limit sample to failed search chain
+
+    struct Cell {
+        turf::Atomic<Hash> hash;
+        turf::Atomic<Value> value;
+    };
+
+    struct Table {
+        const ureg sizeMask;                    // a power of two minus one
+        const ureg limitNumValues;
+        turf::Atomic<sreg> cellsRemaining;
+        turf::Atomic<sreg> valuesRemaining;
+        turf::Mutex mutex;                      // to DCLI the TableMigration (stored in the jobCoordinator)
+        SimpleJobCoordinator jobCoordinator;    // makes all blocked threads participate in the migration
+
+        Table(ureg sizeMask, ureg limitNumValues) : sizeMask(sizeMask), limitNumValues(limitNumValues),
+            cellsRemaining(limitNumValues), valuesRemaining(limitNumValues) {
+        }
+
+        static Table* create(ureg tableSize, ureg limitNumValues) {
+            TURF_ASSERT(turf::util::isPowerOf2(tableSize));
+            Table* table = (Table*) TURF_HEAP.alloc(sizeof(Table) + sizeof(Cell) * tableSize);
+            new(table) Table(tableSize - 1, limitNumValues);
+            for (ureg j = 0; j < tableSize; j++) {
+                table->getCells()[j].hash.storeNonatomic(KeyTraits::NullHash);
+                table->getCells()[j].value.storeNonatomic(Value(ValueTraits::NullValue));
+            }
+            return table;
+        }
+
+        void destroy() {
+            this->Table::~Table();
+            TURF_HEAP.free(this);
+        }
+
+        Cell* getCells() const {
+            return (Cell*) (this + 1);
+        }
+
+        ureg getNumMigrationUnits() const {
+            return sizeMask / TableMigrationUnitSize + 1;
+        }
+    };
+
+    class TableMigration : public SimpleJobCoordinator::Job {
+    public:
+        Map& m_map;
+        Table* m_source;
+        turf::Atomic<ureg> m_sourceIndex;
+        Table* m_destination;
+        turf::Atomic<ureg> m_workerStatus;          // number of workers + end flag
+        turf::Atomic<sreg> m_unitsRemaining;
+
+        TableMigration(Map& map) : m_map(map), m_sourceIndex(0), m_workerStatus(0), m_unitsRemaining(0) {
+            // Caller is responsible for filling in source & destination
+        }
+
+        virtual ~TableMigration() TURF_OVERRIDE {
+            // Destroy source table.
+            m_source->destroy();
+        }
+
+        void destroy() {
+            delete this;
+        }
+
+        bool migrateRange(ureg startIdx);
+        virtual void run() TURF_OVERRIDE;
+    };
+
+    static Cell* find(Hash hash, Table* table) {
+        TURF_TRACE(Linear, 0, "[find] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        ureg sizeMask = table->sizeMask;
+        for (ureg idx = hash;; idx++) {
+            idx &= sizeMask;
+            Cell* cell = table->getCells() + idx;
+            // Load the hash that was there.
+            uptr probeHash = cell->hash.load(turf::Relaxed);
+            if (probeHash == hash) {
+                TURF_TRACE(Linear, 1, "[find] found existing cell", uptr(table), idx);
+                return cell;
+            } else if (probeHash == KeyTraits::NullHash) {
+                return NULL;
+            }
+        }
+    }
+
+    // FIXME: Possible optimization: Dedicated insert for migration? It wouldn't check for InsertResult_AlreadyFound.
+    enum InsertResult {
+        InsertResult_AlreadyFound,
+        InsertResult_InsertedNew,
+        InsertResult_Overflow
+    };
+    static InsertResult insert(Hash hash, Table* table, Cell*& cell) {
+        TURF_TRACE(Linear, 2, "[insert] called", uptr(table), hash);
+        TURF_ASSERT(table);
+        TURF_ASSERT(hash != KeyTraits::NullHash);
+        ureg sizeMask = table->sizeMask;
+
+        for (ureg idx = hash;; idx++) {
+            idx &= sizeMask;
+            cell = table->getCells() + idx;
+            // Load the existing hash.
+            uptr probeHash = cell->hash.load(turf::Relaxed);
+            if (probeHash == hash) {
+                TURF_TRACE(Linear, 3, "[insert] found existing cell", uptr(table), idx);
+                return InsertResult_AlreadyFound;       // Key found in table. Return the existing cell.
+            }
+            if (probeHash == KeyTraits::NullHash) {
+                // It's an empty cell. Try to reserve it.
+                // But first, decrement cellsRemaining to ensure we have permission to create new getCells().
+                s32 prevCellsRemaining = table->cellsRemaining.fetchSub(1, turf::Relaxed);
+                if (prevCellsRemaining <= 0) {
+                    // Table is overpopulated.
+                    TURF_TRACE(Linear, 4, "[insert] ran out of cellsRemaining", prevCellsRemaining, 0);
+                    table->cellsRemaining.fetchAdd(1, turf::Relaxed);    // Undo cellsRemaining decrement
+                    return InsertResult_Overflow;
+                }
+                // Try to reserve this cell.
+                uptr prevHash = cell->hash.compareExchange(KeyTraits::NullHash, hash, turf::Relaxed);
+                if (prevHash == KeyTraits::NullHash) {
+                    // Success. We reserved a new cell.
+                    TURF_TRACE(Linear, 5, "[insert] reserved cell", prevCellsRemaining, idx);
+                    return InsertResult_InsertedNew;
+                }
+                // There was a race and another thread reserved that cell from under us.
+                TURF_TRACE(Linear, 6, "[insert] detected race to reserve cell", ureg(hash), idx);
+                table->cellsRemaining.fetchAdd(1, turf::Relaxed);        // Undo cellsRemaining decrement
+                if (prevHash == hash) {
+                    TURF_TRACE(Linear, 7, "[insert] race reserved same hash", ureg(hash), idx);
+                    return InsertResult_AlreadyFound;       // They inserted the same key. Return the existing cell.
+                }
+            }
+            // Try again in the next cell.
+        }
+    }
+
+    static void beginTableMigration(Map& map, Table* table) {
+        // Create new migration by DCLI.
+        TURF_TRACE(Linear, 8, "[beginTableMigration] called", 0, 0);
+        SimpleJobCoordinator::Job* job = table->jobCoordinator.loadConsume();
+        if (job) {
+            TURF_TRACE(Linear, 9, "[beginTableMigration] new migration already exists", 0, 0);
+        } else {
+            turf::LockGuard<turf::Mutex> guard(table->mutex);
+            job = table->jobCoordinator.loadConsume();  // Non-atomic would be sufficient, but that's OK.
+            if (job) {
+                TURF_TRACE(Linear, 10, "[beginTableMigration] new migration already exists (double-checked)", 0, 0);
+            } else {
+                // Determine new migration size and cap the number of values that can be added concurrent to the migration.
+                sreg oldValuesLimit = table->limitNumValues;
+                sreg oldValuesRemaining = table->valuesRemaining.load(turf::Relaxed);
+                sreg oldValuesInUse = oldValuesLimit - oldValuesRemaining;
+            calculateNextTableSize:
+                sreg nextTableSize = turf::util::roundUpPowerOf2(oldValuesInUse * 2);
+                sreg nextLimitNumValues = nextTableSize * 3 / 4;
+                if (nextLimitNumValues < oldValuesLimit) {
+                    // Set the new limitNumValues on the *current* table.
+                    // This prevents other threads, while the migration is in progress, from concurrently
+                    // re-inserting more values than the new table can hold.
+                    // To set the new limitNumValues on the current table in an atomic fashion,
+                    // we update its valuesRemaining via CAS loop:
+                    for(;;) {
+                        // We must recalculate desiredValuesRemaining on each iteration of the CAS loop
+                        oldValuesInUse = oldValuesLimit - oldValuesRemaining;
+                        sreg desiredValuesRemaining = nextLimitNumValues - oldValuesInUse;
+                        if (desiredValuesRemaining < 0) {
+                            TURF_TRACE(Linear, 11, "[table] restarting valuesRemaining CAS loop", nextLimitNumValues, desiredValuesRemaining);
+                            // Must recalculate nextTableSize. Goto, baby!
+                            goto calculateNextTableSize;
+                        }
+                        if (table->valuesRemaining.compareExchangeWeak(oldValuesRemaining, desiredValuesRemaining, turf::Relaxed, turf::Relaxed))
+                            break; // Success!
+                        // CAS failed because table->valuesRemaining was modified by another thread.
+                        // An updated value has been reloaded into oldValuesRemaining (modified by reference).
+                        // Recalculate desiredValuesRemaining to account for the updated value, and try again.
+                        TURF_TRACE(Linear, 12, "[table] valuesRemaining CAS failed", oldValuesRemaining, desiredValuesRemaining);
+                    }
+                }
+                // Now we are assured that the new table will not become overpopulated during the migration process.
+                // Create new migration.
+                TableMigration* migration = new TableMigration(map);
+                migration->m_source = table;
+                migration->m_destination = Table::create(nextTableSize, nextLimitNumValues);
+                migration->m_unitsRemaining.storeNonatomic(table->getNumMigrationUnits());
+                // Publish the new migration.
+                table->jobCoordinator.storeRelease(migration);
+            }
+        }
+    }
+}; // Linear
+
+template<class Map>
+bool Linear<Map>::TableMigration::migrateRange(ureg startIdx) {
+    ureg srcSizeMask = m_source->sizeMask;
+    ureg endIdx = turf::util::min(startIdx + TableMigrationUnitSize, srcSizeMask + 1);
+    sreg valuesMigrated = 0;
+    // Iterate over source range.
+    for (ureg srcIdx = startIdx; srcIdx < endIdx; srcIdx++) {
+        Cell* srcCell = m_source->getCells() + (srcIdx & srcSizeMask);
+        Hash srcHash;
+        Value srcValue;
+        // Fetch the srcHash and srcValue.
+        for (;;) {
+            srcHash = srcCell->hash.load(turf::Relaxed);
+            if (srcHash == KeyTraits::NullHash) {
+                // An unused cell. Try to put a Redirect marker in its value.
+                srcValue = srcCell->value.compareExchange(Value(ValueTraits::NullValue), Value(ValueTraits::Redirect), turf::Relaxed);
+                if (srcValue == Value(ValueTraits::Redirect)) {
+                    // srcValue is already marked Redirect due to previous incomplete migration.
+                    TURF_TRACE(Linear, 13, "[migrateRange] empty cell already redirected", uptr(m_source), srcIdx);
+                    break;
+                }
+                if (srcValue == Value(ValueTraits::NullValue))
+                    break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                TURF_TRACE(Linear, 14, "[migrateRange] race to insert key", uptr(m_source), srcIdx);
+                // Otherwise, somebody just claimed the cell. Read srcHash again...
+            } else {
+                // Check for deleted/uninitialized value.
+                srcValue = srcCell->value.load(turf::Relaxed);
+                if (srcValue == Value(ValueTraits::NullValue)) {
+                    // Try to put a Redirect marker.
+                    if (srcCell->value.compareExchangeStrong(srcValue, Value(ValueTraits::Redirect), turf::Relaxed))
+                        break;  // Redirect has been placed. Break inner loop, continue outer loop.
+                    TURF_TRACE(Linear, 15, "[migrateRange] race to insert value", uptr(m_source), srcIdx);
+                }
+                
+                // We've got a key/value pair to migrate.
+                // Reserve a destination cell in the destination.
+                TURF_ASSERT(srcHash != KeyTraits::NullHash);
+                TURF_ASSERT(srcValue != Value(ValueTraits::NullValue));
+                TURF_ASSERT(srcValue != Value(ValueTraits::Redirect));   // Incomplete/concurrent migrations are impossible.
+                Cell* dstCell;
+                InsertResult result = insert(srcHash, m_destination, dstCell);
+                // During migration, a hash can only exist in one place among all the source tables,
+                // and it is only migrated by one thread. Therefore, the hash will never already exist
+                // in the destination table:
+                TURF_ASSERT(result != InsertResult_AlreadyFound);
+                TURF_ASSERT(result != InsertResult_Overflow);
+                // Migrate the old value to the new cell.
+                for (;;) {
+                    // Copy srcValue to the destination.
+                    dstCell->value.store(srcValue, turf::Relaxed);
+                    // Try to place a Redirect marker in srcValue.
+                    Value doubleCheckedSrcValue = srcCell->value.compareExchange(srcValue, Value(ValueTraits::Redirect), turf::Relaxed);
+                    TURF_ASSERT(doubleCheckedSrcValue != Value(ValueTraits::Redirect)); // Only one thread can redirect a cell at a time.
+                    if (doubleCheckedSrcValue == srcValue) {
+                        // No racing writes to the src. We've successfully placed the Redirect marker.
+                        // srcValue was non-NULL when we decided to migrate it, but it may have changed to NULL
+                        // by a late-arriving erase.
+                        if (srcValue == Value(ValueTraits::NullValue))
+                            TURF_TRACE(Linear, 16, "[migrateRange] racing update was erase", uptr(m_source), srcIdx);
+                        else
+                            valuesMigrated++;
+                        break;
+                    }
+                    // There was a late-arriving write (or erase) to the src. Migrate the new value and try again.
+                    TURF_TRACE(Linear, 17, "[migrateRange] race to update migrated value", uptr(m_source), srcIdx);
+                    srcValue = doubleCheckedSrcValue;
+                }
+                // Cell successfully migrated. Proceed to next source cell.
+                break;
+            }
+        }
+    }
+    sreg prevValuesRemaining = m_destination->valuesRemaining.fetchSub(valuesMigrated, turf::Relaxed);
+    TURF_ASSERT(valuesMigrated <= prevValuesRemaining);
+    TURF_UNUSED(prevValuesRemaining);
+    // Range has been migrated successfully.
+    return true;
+}
+
+template <class Map>
+void Linear<Map>::TableMigration::run() {
+    // Conditionally increment the shared # of workers.
+    ureg probeStatus = m_workerStatus.load(turf::Relaxed);
+    do {
+        if (probeStatus & 1) {
+            // End flag is already set, so do nothing.
+            TURF_TRACE(Linear, 18, "[TableMigration::run] already ended", uptr(this), 0);
+            return;
+        }
+    } while (!m_workerStatus.compareExchangeWeak(probeStatus, probeStatus + 2, turf::Relaxed, turf::Relaxed));
+    // # of workers has been incremented, and the end flag is clear.
+    TURF_ASSERT((probeStatus & 1) == 0);
+
+    // Loop over all migration units in the source table.
+    for (;;) {
+        if (m_workerStatus.load(turf::Relaxed) & 1) {
+            TURF_TRACE(Linear, 19, "[TableMigration::run] detected end flag set", uptr(this), 0);
+            goto endMigration;
+        }
+        ureg startIdx = m_sourceIndex.fetchAdd(TableMigrationUnitSize, turf::Relaxed);
+        if (startIdx >= m_source->sizeMask + 1)
+            break;   // No more migration units.
+        migrateRange(startIdx);
+        sreg prevRemaining = m_unitsRemaining.fetchSub(1, turf::Relaxed);
+        TURF_ASSERT(prevRemaining > 0);
+        if (prevRemaining == 1) {
+            // That was the last chunk to migrate.
+            m_workerStatus.fetchOr(1, turf::Relaxed);
+            goto endMigration;
+        }
+    }
+    TURF_TRACE(Linear, 20, "[TableMigration::run] out of migration units", uptr(this), 0);
+
+endMigration:
+    // Decrement the shared # of workers.
+    probeStatus = m_workerStatus.fetchSub(2, turf::AcquireRelease);    // AcquireRelease makes all previous writes visible to the last worker thread.
+    if (probeStatus >= 4) {
+        // There are other workers remaining. Return here so that only the very last worker will proceed.
+        TURF_TRACE(Linear, 21, "[TableMigration::run] not the last worker", uptr(this), uptr(probeStatus));
+        return;
+    }
+
+    // We're the very last worker thread.
+    // Publish the new subtree.
+    TURF_ASSERT(probeStatus == 3);
+    m_map.publishTableMigration(this);
+    // End the jobCoodinator.
+    m_source->jobCoordinator.end();
+
+    // We're done with this TableMigration. Queue it for GC.
+    DefaultQSBR.enqueue(&TableMigration::destroy, this);
+}
+
+} // namespace details
+} // namespace junction
+
+#endif // JUNCTION_DETAILS_LINEAR_H
diff --git a/junction/extra/MapAdapter.h b/junction/extra/MapAdapter.h
new file mode 100644 (file)
index 0000000..9897d94
--- /dev/null
@@ -0,0 +1,24 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_MAPADAPTER_H
+#define JUNCTION_EXTRA_MAPADAPTER_H
+
+#include <junction/Core.h>
+
+#ifndef JUNCTION_IMPL_MAPADAPTER_PATH
+#define JUNCTION_IMPL_MAPADAPTER_PATH "junction/extra/impl/MapAdapter_Grampa.h"
+#endif
+
+#include JUNCTION_IMPL_MAPADAPTER_PATH
+
+#endif // JUNCTION_EXTRA_MAPADAPTER_H
diff --git a/junction/extra/MemHook_NBDS.cpp b/junction/extra/MemHook_NBDS.cpp
new file mode 100644 (file)
index 0000000..c736748
--- /dev/null
@@ -0,0 +1,29 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <turf/Heap.h>
+
+#if JUNCTION_WITH_NBDS && NBDS_USE_TURF_HEAP
+extern "C" {
+void mem_init (void) {
+}
+
+void *nbd_malloc (size_t n) {
+    return TURF_HEAP.alloc(n);
+}
+
+void nbd_free (void *x) {
+    TURF_HEAP.free(x);
+}
+} // extern "C"
+#endif // JUNCTION_WITH_NBDS && NBDS_USE_TURF_HEAP
diff --git a/junction/extra/MemHook_TBB.cpp b/junction/extra/MemHook_TBB.cpp
new file mode 100644 (file)
index 0000000..46dd76b
--- /dev/null
@@ -0,0 +1,32 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <turf/Heap.h>
+
+#if JUNCTION_WITH_TBB && TBB_USE_TURF_HEAP
+void* tbbWrap_malloc(size_t size) {
+    return TURF_HEAP.alloc(size);
+}
+
+void  tbbWrap_free(void* ptr) {
+    TURF_HEAP.free(ptr);
+}
+
+void* tbbWrap_padded_allocate(size_t size, size_t alignment) {
+    return TURF_HEAP.allocAligned(size, alignment);
+}
+
+void  tbbWrap_padded_free(void* ptr) {
+    TURF_HEAP.free(ptr);
+}
+#endif // JUNCTION_WITH_TBB && TBB_USE_TURF_HEAP
diff --git a/junction/extra/impl/MapAdapter_CDS_Cuckoo.h b/junction/extra/impl/MapAdapter_CDS_Cuckoo.h
new file mode 100644 (file)
index 0000000..bb22a67
--- /dev/null
@@ -0,0 +1,112 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_CUCKOO_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_CUCKOO_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_CDS
+#error "You must configure with JUNCTION_WITH_CDS=1!"
+#endif
+
+#include <junction/MapTraits.h>
+#include <cds/init.h>
+#include <cds/gc/hp.h>
+#include <memory.h>     // memcpy required by cuckoo_map.h
+#include <cds/container/cuckoo_map.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "CDS CuckooMap";
+    
+    cds::gc::HP *m_hpGC;
+
+    MapAdapter(ureg) {
+        cds::Initialize();
+        m_hpGC = new cds::gc::HP;
+    }
+
+    ~MapAdapter() {
+        delete m_hpGC;
+        cds::Terminate();
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+            cds::threading::Manager::attachThread();
+        }
+
+        void unregisterThread() {
+            cds::threading::Manager::detachThread();
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        struct Hash1 {
+            size_t operator()(u32 s) const {
+                return junction::hash(s);
+            }
+        };
+
+        struct Hash2 {
+            size_t operator()(u32 s) const {
+                return junction::hash(s + 0x9e3779b9);
+            }
+        };
+
+        struct Traits : cds::container::cuckoo::traits {
+            typedef std::equal_to<u32> equal_to;
+            typedef cds::opt::hash_tuple<Hash1, Hash2> hash;
+        };
+
+        cds::container::CuckooMap<u32, void*, Traits> m_map;
+
+    public:
+        Map(ureg capacity) : m_map() {
+        }
+
+        void insert(u32 key, void* value) {
+            m_map.insert(key, value);
+        }
+
+        void* get(u32 key) {
+            void* result = NULL;
+            m_map.find(key, [&result](std::pair<const u32, void*>& item){ result = item.second; });
+            return result;
+        }
+
+        void erase(u32 key) {
+            m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return maxPopulation / 4;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_CUCKOO_H
diff --git a/junction/extra/impl/MapAdapter_CDS_Michael.h b/junction/extra/impl/MapAdapter_CDS_Michael.h
new file mode 100644 (file)
index 0000000..ce600f3
--- /dev/null
@@ -0,0 +1,115 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_MICHAEL_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_MICHAEL_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_CDS
+#error "You must configure with JUNCTION_WITH_CDS=1!"
+#endif
+
+#include <junction/MapTraits.h>
+#include <cds/init.h>
+#include <cds/gc/hp.h>
+#include <cds/container/michael_kvlist_hp.h>
+#include <cds/container/michael_map.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "CDS MichaelKVList";
+
+    cds::gc::HP *m_hpGC;
+
+    MapAdapter(ureg) {
+        cds::Initialize();
+        m_hpGC = new cds::gc::HP;
+    }
+
+    ~MapAdapter() {
+        delete m_hpGC;
+        cds::Terminate();
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+            cds::threading::Manager::attachThread();
+        }
+
+        void unregisterThread() {
+            cds::threading::Manager::detachThread();
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        // List traits based on std::less predicate
+        struct ListTraits : public cds::container::michael_list::traits
+        {
+            typedef std::less<u32>      less;
+        };
+
+        // Ordered list
+        typedef cds::container::MichaelKVList< cds::gc::HP, u32, void*, ListTraits> OrderedList;
+
+        // Map traits
+        struct MapTraits : public cds::container::michael_map::traits
+        {
+            struct hash {
+                size_t operator()( u32 i ) const
+                {
+                    return cds::opt::v::hash<u32>()( i );
+                }
+            };
+        };
+
+        cds::container::MichaelHashMap<cds::gc::HP, OrderedList, MapTraits> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity, 1) {
+        }
+
+        void insert(u32 key, void* value) {
+            m_map.insert(key, value);
+        }
+
+        void* get(u32 key) {
+            void* result = NULL;
+            m_map.find(key, [&result](std::pair<const u32, void*>& item){ result = item.second; });
+            return result;
+        }
+
+        void erase(u32 key) {
+            m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return maxPopulation / 4;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_CDS_MICHAEL_H
diff --git a/junction/extra/impl/MapAdapter_Folly.h b/junction/extra/impl/MapAdapter_Folly.h
new file mode 100644 (file)
index 0000000..02d54a6
--- /dev/null
@@ -0,0 +1,79 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_FOLLY_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_FOLLY_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_FOLLY
+#error "You must configure with JUNCTION_WITH_FOLLY=1!"
+#endif
+
+#include <folly/AtomicHashMap.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Folly AtomicHashMap";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        folly::AtomicHashMap<u32, void*> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity) {
+        }
+
+        void insert(u32 key, void* value) {
+            m_map.insert(std::make_pair(key, value));
+        }
+
+        void* get(u32 key) {
+            auto ret = m_map.find(key);
+            return ret != m_map.end() ? ret->second : NULL;
+        }
+
+        void erase(u32 key) {
+            m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return maxPopulation / 4;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_FOLLY_H
diff --git a/junction/extra/impl/MapAdapter_Grampa.h b/junction/extra/impl/MapAdapter_Grampa.h
new file mode 100644 (file)
index 0000000..185fa94
--- /dev/null
@@ -0,0 +1,62 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_GRAMPA_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_GRAMPA_H
+
+#include <junction/Core.h>
+#include <junction/QSBR.h>
+#include <junction/ConcurrentMap_Grampa.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Junction Grampa map";
+    
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    private:
+        QSBR::Context m_qsbrContext;
+        
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+            m_qsbrContext = DefaultQSBR.createContext();
+        }
+
+        void unregisterThread() {
+            DefaultQSBR.destroyContext(m_qsbrContext);
+        }
+
+        void update() {
+            DefaultQSBR.update(m_qsbrContext);
+        }
+    };
+
+    typedef ConcurrentMap_Grampa<u32, void*> Map;
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return turf::util::roundUpPowerOf2(maxPopulation / 4);
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_GRAMPA_H
diff --git a/junction/extra/impl/MapAdapter_LeapFrog.h b/junction/extra/impl/MapAdapter_LeapFrog.h
new file mode 100644 (file)
index 0000000..02b09ca
--- /dev/null
@@ -0,0 +1,62 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_LEAPFROG_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_LEAPFROG_H
+
+#include <junction/Core.h>
+#include <junction/QSBR.h>
+#include <junction/ConcurrentMap_LeapFrog.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Junction LeapFrog map";
+    
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    private:
+        QSBR::Context m_qsbrContext;
+        
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+        
+        void registerThread() {
+            m_qsbrContext = DefaultQSBR.createContext();
+        }
+        
+        void unregisterThread() {
+            DefaultQSBR.destroyContext(m_qsbrContext);
+        }
+        
+        void update() {
+            DefaultQSBR.update(m_qsbrContext);
+        }
+    };
+    
+    typedef ConcurrentMap_LeapFrog<u32, void*> Map;
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return turf::util::roundUpPowerOf2(maxPopulation / 4);
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_LEAPFROG_H
diff --git a/junction/extra/impl/MapAdapter_Linear.h b/junction/extra/impl/MapAdapter_Linear.h
new file mode 100644 (file)
index 0000000..525eb74
--- /dev/null
@@ -0,0 +1,62 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_H
+
+#include <junction/Core.h>
+#include <junction/QSBR.h>
+#include <junction/ConcurrentMap_Linear.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Junction Linear map";
+    
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    private:
+        QSBR::Context m_qsbrContext;
+        
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+        
+        void registerThread() {
+            m_qsbrContext = DefaultQSBR.createContext();
+        }
+        
+        void unregisterThread() {
+            DefaultQSBR.destroyContext(m_qsbrContext);
+        }
+        
+        void update() {
+            DefaultQSBR.update(m_qsbrContext);
+        }
+    };
+    
+    typedef ConcurrentMap_Linear<u32, void*> Map;
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return turf::util::roundUpPowerOf2(maxPopulation / 4);
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_H
diff --git a/junction/extra/impl/MapAdapter_Linear_Mutex.h b/junction/extra/impl/MapAdapter_Linear_Mutex.h
new file mode 100644 (file)
index 0000000..4339596
--- /dev/null
@@ -0,0 +1,79 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_MUTEX_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_MUTEX_H
+
+#include <junction/Core.h>
+#include <junction/SingleMap_Linear.h>
+#include <turf/Mutex.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Single + Mutex";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        turf::Mutex m_mutex;
+        SingleMap_Linear<u32, void*> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity) {
+        }
+
+        void insert(u32 key, void* value) {
+            turf::LockGuard<turf::Mutex> guard(m_mutex);
+            m_map.insert(key, value);
+        }
+
+        void* get(u32 key) {
+            turf::LockGuard<turf::Mutex> guard(m_mutex);
+            return m_map.get(key);
+        }
+    
+        void* erase(u32 key) {
+            turf::LockGuard<turf::Mutex> guard(m_mutex);
+            return m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return turf::util::roundUpPowerOf2(maxPopulation / 4);
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_MUTEX_H
diff --git a/junction/extra/impl/MapAdapter_Linear_RWLock.h b/junction/extra/impl/MapAdapter_Linear_RWLock.h
new file mode 100644 (file)
index 0000000..b4e34aa
--- /dev/null
@@ -0,0 +1,79 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_RWLOCK_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_RWLOCK_H
+
+#include <junction/Core.h>
+#include <junction/SingleMap_Linear.h>
+#include <turf/RWLock.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Single + RWLock";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        turf::RWLock m_rwLock;
+        SingleMap_Linear<u32, void*> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity) {
+        }
+
+        void insert(u32 key, void* value) {
+            turf::ExclusiveLockGuard<turf::RWLock> guard(m_rwLock);
+            m_map.insert(key, value);
+        }
+
+        void* get(u32 key) {
+            turf::SharedLockGuard<turf::RWLock> guard(m_rwLock);
+            return m_map.get(key);
+        }
+    
+        void erase(u32 key) {
+            turf::ExclusiveLockGuard<turf::RWLock> guard(m_rwLock);
+            m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return turf::util::roundUpPowerOf2(maxPopulation / 4);
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_LINEAR_RWLOCK_H
diff --git a/junction/extra/impl/MapAdapter_NBDS.h b/junction/extra/impl/MapAdapter_NBDS.h
new file mode 100644 (file)
index 0000000..43ed97b
--- /dev/null
@@ -0,0 +1,93 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_NBDS_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_NBDS_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_NBDS
+#error "You must configure with JUNCTION_WITH_NBDS=1!"
+#endif
+
+extern "C" {
+#include <runtime.h>
+#include <rcu.h>
+#include <../runtime/rlocal.h>
+#include <hashtable.h>
+}
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "nbds hashtable_t";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    private:
+        ureg m_threadIndex;
+
+    public:
+        ThreadContext(MapAdapter&, ureg threadIndex) : m_threadIndex(threadIndex) {
+        }
+
+        void registerThread() {
+            rcu_thread_init(m_threadIndex);
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+            rcu_update();
+        }
+    };
+
+    class Map {
+    private:
+        hashtable_t* m_map;
+
+    public:
+        Map(ureg) {
+            m_map = ht_alloc(NULL);
+        }
+
+        ~Map() {
+            ht_free(m_map);
+        }
+
+        void insert(u32 key, void* value) {
+            ht_cas(m_map, key, CAS_EXPECT_WHATEVER, (map_val_t) value);
+        }
+
+        void* get(u32 key) {
+            return (void*) ht_get(m_map, key);
+        }
+
+        void erase(u32 key) {
+            ht_remove(m_map, key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg) {
+        return 0;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_NBDS_H
diff --git a/junction/extra/impl/MapAdapter_Null.h b/junction/extra/impl/MapAdapter_Null.h
new file mode 100644 (file)
index 0000000..524f6e3
--- /dev/null
@@ -0,0 +1,67 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_NULL_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_NULL_H
+
+#include <junction/Core.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Null";
+    
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    public:
+        Map(ureg) {
+        }
+
+        void insert(u32, void*) {
+        }
+
+        void* get(u32) {
+            return NULL;
+        }
+
+        void erase(u32) {
+        }
+    };
+
+    static ureg getInitialCapacity(ureg) {
+        return 0;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_NULL_H
diff --git a/junction/extra/impl/MapAdapter_StdMap.h b/junction/extra/impl/MapAdapter_StdMap.h
new file mode 100644 (file)
index 0000000..4d287cc
--- /dev/null
@@ -0,0 +1,106 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
+
+#include <junction/Core.h>
+#include <map>
+#include <mutex>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "std::map + std::mutex";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        std::mutex m_mutex;
+        typedef std::map<u32, void*> MapType;
+        MapType m_map;
+
+    public:
+        Map(ureg) {
+        }
+
+        void insert(u32 key, void* value) {
+            std::lock_guard<std::mutex> guard(m_mutex);
+            m_map.insert(std::make_pair(key, value));
+        }
+
+        void* get(u32 key) {
+            std::lock_guard<std::mutex> guard(m_mutex);
+            MapType::iterator iter = m_map.find(key);
+            return (iter == m_map.end()) ? NULL : iter->second;
+        }
+    
+        void erase(u32 key) {
+            std::lock_guard<std::mutex> guard(m_mutex);
+            m_map.erase(key);
+        }
+
+        class Iterator {
+        private:
+            Map& m_map;
+            MapType::iterator m_iter;
+
+        public:
+            Iterator(Map& map) : m_map(map), m_iter(m_map.m_map.begin()) {
+            }
+
+            void next() {
+                m_iter++;
+            }
+
+            bool isValid() const {
+                return m_iter != m_map.m_map.end();
+            }
+
+            u32 getKey() const {
+                return m_iter->first;
+            }
+
+            void* getValue() const {
+                return m_iter->second;
+            }
+        };
+    };
+
+    static ureg getInitialCapacity(ureg) {
+        return 0;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_STDMAP_H
diff --git a/junction/extra/impl/MapAdapter_TBB.h b/junction/extra/impl/MapAdapter_TBB.h
new file mode 100644 (file)
index 0000000..a87a465
--- /dev/null
@@ -0,0 +1,82 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_TBB_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_TBB_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_TBB
+#error "You must configure with JUNCTION_WITH_TBB=1!"
+#endif
+
+#include <tbb/concurrent_hash_map.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Intel TBB concurrent_hash_map";
+
+    MapAdapter(ureg) {
+    }
+
+    class ThreadContext {
+    public:
+        ThreadContext(MapAdapter&, ureg) {
+        }
+
+        void registerThread() {
+        }
+
+        void unregisterThread() {
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        tbb::concurrent_hash_map<u32, void*> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity) {
+        }
+
+        void insert(u32 key, void* value) {
+            m_map.insert(std::make_pair(key, value));
+        }
+
+        void* get(u32 key) {
+            tbb::concurrent_hash_map<u32, void*>::const_accessor result;
+            if (m_map.find(result, key))
+                return result->second;
+            else
+                return NULL;
+        }
+
+        void erase(u32 key) {
+            m_map.erase(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return maxPopulation / 4;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_TBB_H
diff --git a/junction/extra/impl/MapAdapter_Tervel.h b/junction/extra/impl/MapAdapter_Tervel.h
new file mode 100644 (file)
index 0000000..d00320d
--- /dev/null
@@ -0,0 +1,90 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_EXTRA_IMPL_MAPADAPTER_TERVEL_H
+#define JUNCTION_EXTRA_IMPL_MAPADAPTER_TERVEL_H
+
+#include <junction/Core.h>
+
+#if !JUNCTION_WITH_TERVEL
+#error "You must configure with JUNCTION_WITH_TERVEL=1!"
+#endif
+
+#include <tervel/util/tervel.h>
+#include <tervel/containers/wf/hash-map/wf_hash_map.h>
+
+namespace junction {
+namespace extra {
+
+class MapAdapter {
+public:
+    static TURF_CONSTEXPR const char* MapName = "Tervel HashMap";
+
+    tervel::Tervel m_tervel;
+
+    MapAdapter(ureg numThreads) : m_tervel(numThreads) {
+    }
+
+    class ThreadContext {
+    public:
+        MapAdapter& m_adapter;
+        tervel::ThreadContext* m_context;
+
+        ThreadContext(MapAdapter& adapter, ureg) : m_adapter(adapter), m_context(NULL) {
+        }
+
+        void registerThread() {
+            m_context = new tervel::ThreadContext(&m_adapter.m_tervel);
+        }
+
+        void unregisterThread() {
+            delete m_context;
+        }
+
+        void update() {
+        }
+    };
+
+    class Map {
+    private:
+        tervel::containers::wf::HashMap<u64, u64> m_map;
+
+    public:
+        Map(ureg capacity) : m_map(capacity, 3) {
+        }
+
+        void insert(u32 key, void* value) {
+            m_map.insert(key, (u64) value);
+        }
+
+        void* get(u32 key) {
+            typename tervel::containers::wf::HashMap<u64, u64>::ValueAccessor va;
+            if (m_map.at(key, va))
+                return (void*) *va.value();
+            else
+                return NULL;
+        }
+
+        void erase(u32 key) {
+            m_map.remove(key);
+        }
+    };
+
+    static ureg getInitialCapacity(ureg maxPopulation) {
+        return maxPopulation / 4;
+    }
+};
+
+} // namespace extra
+} // namespace junction
+
+#endif // JUNCTION_EXTRA_IMPL_MAPADAPTER_TERVEL_H
diff --git a/junction/striped/AutoResetEvent.h b/junction/striped/AutoResetEvent.h
new file mode 100644 (file)
index 0000000..ca7e0dd
--- /dev/null
@@ -0,0 +1,55 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_STRIPED_AUTORESETEVENT_H
+#define JUNCTION_STRIPED_AUTORESETEVENT_H
+
+#include <junction/Core.h>
+#include <junction/striped/ConditionBank.h>
+
+namespace junction {
+namespace striped {
+
+class AutoResetEvent {
+private:
+    JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
+    bool m_status;
+
+public:
+    AutoResetEvent(bool status) : m_status(status) {
+    }
+
+    void wait() {
+        ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+        turf::LockGuard<turf::Mutex> guard(pair.mutex);
+        while (!m_status)
+            pair.condVar.wait(guard);
+        m_status = false;
+    }
+
+    void signal() {
+        ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+        turf::LockGuard<turf::Mutex> guard(pair.mutex);
+        if (!m_status) {
+            m_status = true;
+            // FIXME: Is there a more efficient striped::Mutex implementation that is safe from deadlock?
+            // This approach will wake up too many threads when there is heavy contention.
+            // However, if we don't wakeAll(), we will miss wakeups, since ConditionPairs are shared.
+            pair.condVar.wakeAll();
+        }
+    }
+};
+
+} // namespace striped
+} // namespace junction
+
+#endif // JUNCTION_STRIPED_AUTORESETEVENT_H
diff --git a/junction/striped/ConditionBank.cpp b/junction/striped/ConditionBank.cpp
new file mode 100644 (file)
index 0000000..30aec87
--- /dev/null
@@ -0,0 +1,37 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <junction/striped/ConditionBank.h>
+
+#if JUNCTION_USE_STRIPING
+
+namespace junction {
+namespace striped {
+
+ConditionBank DefaultConditionBank;
+
+ConditionPair* ConditionBank::initialize() {
+    m_initSpinLock.lock();
+    ConditionPair* pairs = m_pairs.loadNonatomic();
+    if (!pairs) {
+        pairs = new ConditionPair[SizeMask + 1];
+        m_pairs.store(pairs, turf::Release);
+    }
+    m_initSpinLock.unlock();
+    return pairs;
+}
+
+} // namespace striped
+} // namespace junction
+
+#endif // JUNCTION_USE_STRIPING
diff --git a/junction/striped/ConditionBank.h b/junction/striped/ConditionBank.h
new file mode 100644 (file)
index 0000000..1c3e6d3
--- /dev/null
@@ -0,0 +1,67 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_STRIPED_CONDITIONBANK_H
+#define JUNCTION_STRIPED_CONDITIONBANK_H
+
+#include <junction/Core.h>
+#include <junction/striped/ConditionPair.h>
+
+#if JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping enabled
+//-----------------------------------
+#include <turf/impl/Mutex_SpinLock.h>
+#include <turf/Util.h>
+
+namespace junction {
+namespace striped {
+
+class ConditionBank {
+private:
+    static const ureg SizeMask = 1023;
+    turf::Mutex_SpinLock m_initSpinLock;
+    turf::Atomic<ConditionPair*> m_pairs;
+
+    ConditionPair* initialize();
+
+public:
+    ConditionPair& get(void* ptr) {
+        ConditionPair* pairs = m_pairs.load(turf::Consume);
+        if (!pairs) {
+            pairs = initialize();
+        }
+        ureg index = turf::util::avalanche(uptr(ptr)) & SizeMask;
+        return pairs[index];
+    }
+};
+
+extern ConditionBank DefaultConditionBank;
+
+} // namespace striped
+} // namespace junction
+
+#define JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
+#define JUNCTION_STRIPED_CONDITIONBANK_GET(objectPtr)   (junction::striped::DefaultConditionBank.get(objectPtr))
+
+#else // JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping disabled
+//-----------------------------------
+#define JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()  junction::striped::ConditionPair m_conditionPair;
+#define JUNCTION_STRIPED_CONDITIONBANK_GET(objectPtr)   ((objectPtr)->m_conditionPair)
+
+#endif // JUNCTION_USE_STRIPING
+
+#endif // JUNCTION_STRIPED_CONDITIONBANK_H
diff --git a/junction/striped/ConditionPair.h b/junction/striped/ConditionPair.h
new file mode 100644 (file)
index 0000000..c453cd7
--- /dev/null
@@ -0,0 +1,31 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_STRIPED_CONDITIONPAIR_H
+#define JUNCTION_STRIPED_CONDITIONPAIR_H
+
+#include <junction/Core.h>
+#include <turf/Mutex.h>
+#include <turf/ConditionVariable.h>
+
+namespace junction {
+namespace striped {
+
+struct ConditionPair {
+    turf::Mutex mutex;
+    turf::ConditionVariable condVar;
+};
+
+} // namespace striped
+} // namespace junction
+
+#endif // JUNCTION_STRIPED_CONDITIONPAIR_H
diff --git a/junction/striped/ManualResetEvent.h b/junction/striped/ManualResetEvent.h
new file mode 100644 (file)
index 0000000..e902f9a
--- /dev/null
@@ -0,0 +1,99 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_STRIPED_MANUALRESETEVENT_H
+#define JUNCTION_STRIPED_MANUALRESETEVENT_H
+
+#include <junction/Core.h>
+
+#if JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping enabled
+//-----------------------------------
+#include <junction/striped/ConditionBank.h>
+
+namespace junction {
+namespace striped {
+
+class ManualResetEvent {
+private:
+    JUNCTION_STRIPED_CONDITIONBANK_DEFINE_MEMBER()
+    static const u8 Signaled = 1;
+    static const u8 HasWaiters = 2;
+    turf::Atomic<u8> m_state;
+
+public:
+    ManualResetEvent(bool initialState = false) : m_state(initialState ? Signaled : 0) {
+    }
+
+    ~ManualResetEvent() {
+    }
+
+    void signal() {
+        u8 prevState = m_state.fetchOr(Signaled, turf::Release);    // Synchronizes-with the load in wait (fast path)
+        if (prevState & HasWaiters) {
+            ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+            turf::LockGuard<turf::Mutex> guard(pair.mutex);   // Prevents the wake from occuring in the middle of wait()'s critical section
+            pair.condVar.wakeAll();
+        }
+    }
+
+    bool isSignaled() const {
+        return m_state.load(turf::Relaxed) & Signaled;
+    }
+
+    void reset() {
+        TURF_ASSERT(0); // FIXME: implement it
+    }
+
+    void wait() {
+        u8 state = m_state.load(turf::Acquire);     // Synchronizes-with the fetchOr in signal (fast path)
+        if ((state & Signaled) == 0) {
+            ConditionPair& pair = JUNCTION_STRIPED_CONDITIONBANK_GET(this);
+            turf::LockGuard<turf::Mutex> guard(pair.mutex);
+            for (;;) {
+                // FIXME: Implement reusable AdaptiveBackoff class and apply it here
+                state = m_state.load(turf::Relaxed);
+                if (state & Signaled)
+                    break;
+                if (state != HasWaiters) {
+                    TURF_ASSERT(state == 0);
+                    if (!m_state.compareExchangeWeak(state, HasWaiters, turf::Relaxed, turf::Relaxed))
+                        continue;
+                }
+                // The lock ensures signal can't wakeAll between the load and the wait
+                pair.condVar.wait(guard);
+            }
+        }
+    }
+};
+
+} // namespace striped
+} // namespace junction
+
+#else // JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping disabled
+//-----------------------------------
+#include <turf/ManualResetEvent.h>
+
+namespace junction {
+namespace striped {
+typedef turf::ManualResetEvent ManualResetEvent;
+} // namespace striped
+} // namespace junction
+
+#endif // JUNCTION_USE_STRIPING
+
+#endif // JUNCTION_STRIPED_MANUALRESETEVENT_H
diff --git a/junction/striped/Mutex.h b/junction/striped/Mutex.h
new file mode 100644 (file)
index 0000000..c88b1ab
--- /dev/null
@@ -0,0 +1,76 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef JUNCTION_STRIPED_MUTEX_H
+#define JUNCTION_STRIPED_MUTEX_H
+
+#include <junction/Core.h>
+
+#if JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping enabled
+//-----------------------------------
+#include <junction/striped/AutoResetEvent.h>
+
+namespace junction {
+namespace striped {
+
+// Not recursive
+class Mutex {
+private:
+    turf::Atomic<sreg> m_status;
+    junction::striped::AutoResetEvent m_event;
+
+    void lockSlow() {
+        while (m_status.exchange(1, turf::Acquire) >= 0)
+            m_event.wait();
+    }
+
+public:
+    Mutex() : m_status(-1), m_event(false) {
+    }
+
+    void lock() {
+        if (m_status.exchange(0, turf::Acquire) >= 0)
+            lockSlow();
+    }
+
+    bool tryLock() {
+        return (m_status.compareExchange(-1, 0, turf::Acquire) < 0);
+    }
+    
+    void unlock() {
+        if (m_status.exchange(-1, turf::Release) > 0)
+            m_event.signal();
+    }
+};
+
+} // namespace striped
+} // namespace junction
+
+#else // JUNCTION_USE_STRIPING
+
+//-----------------------------------
+// Striping disabled
+//-----------------------------------
+#include <turf/Mutex.h>
+
+namespace junction {
+namespace striped {
+typedef turf::Mutex Mutex;
+} // namespace striped
+} // namespace junction
+
+#endif // JUNCTION_USE_STRIPING
+
+#endif // JUNCTION_STRIPED_MUTEX_H
diff --git a/samples/MallocTest/CMakeLists.txt b/samples/MallocTest/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9838328
--- /dev/null
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 2.8.5)
+
+get_filename_component(SAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    # CMAKE_CONFIGURATION_TYPES only reliable if set before project(), and not from an include file
+    set(CMAKE_CONFIGURATION_TYPES "Debug;RelWithAsserts;RelWithDebInfo" CACHE INTERNAL "Build configs")
+    project(${SAMPLE_NAME})
+endif()    
+
+include(../../cmake/AddSample.cmake)
diff --git a/samples/MallocTest/MallocTest.cpp b/samples/MallocTest/MallocTest.cpp
new file mode 100644 (file)
index 0000000..37efc77
--- /dev/null
@@ -0,0 +1,35 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <turf/Heap.h>
+#include <junction/extra/MapAdapter.h>
+#include <iostream>
+
+using namespace turf::intTypes;
+
+int main() {
+    junction::extra::MapAdapter adapter(1);
+    junction::extra::MapAdapter::ThreadContext context(adapter, 0);
+    junction::extra::MapAdapter::Map map(65536);
+
+    ureg population = 0;
+    for (ureg i = 0; i < 100; i++) {
+#if TURF_USE_DLMALLOC && TURF_DLMALLOC_FAST_STATS
+        std::cout << "Population=" << population << ", inUse=" << TURF_HEAP.getInUseBytes() << std::endl;
+#endif
+        for (; population < i * 5000; population++)
+            map.insert(population + 1, (void*) ((population << 2) | 3));
+    }
+
+    return 0;
+}
diff --git a/samples/MapCorrectnessTests/CMakeLists.txt b/samples/MapCorrectnessTests/CMakeLists.txt
new file mode 100644 (file)
index 0000000..b1c771c
--- /dev/null
@@ -0,0 +1,12 @@
+cmake_minimum_required(VERSION 2.8.5)
+
+get_filename_component(SAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    # CMAKE_CONFIGURATION_TYPES only reliable if set before project(), and not from an include file
+    set(CMAKE_CONFIGURATION_TYPES "Debug;RelWithAsserts;RelWithDebInfo" CACHE INTERNAL "Build configs")
+    project(${SAMPLE_NAME})
+endif()    
+
+set(TEST_CHECK_MAP_CONTENTS TRUE CACHE BOOL "Validate contents of the map using its iterator")
+set(JUNCTION_USERCONFIG "junction_userconfig.h.in" CACHE STRING "Custom config for ${SAMPLE_NAME}")
+include(../../cmake/AddSample.cmake)
diff --git a/samples/MapCorrectnessTests/MapCorrectnessTests.cpp b/samples/MapCorrectnessTests/MapCorrectnessTests.cpp
new file mode 100644 (file)
index 0000000..ca7f9d2
--- /dev/null
@@ -0,0 +1,49 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include "TestEnvironment.h"
+#include "TestInsertSameKeys.h"
+#include "TestInsertDifferentKeys.h"
+#include "TestChurn.h"
+#include <turf/extra/Options.h>
+#include <junction/details/Grampa.h>  // for GrampaStats
+
+static const ureg IterationsPerLog = 100;
+
+int main(int argc, const char** argv) {
+    TestEnvironment env;
+
+    TestInsertSameKeys testInsertSameKeys(env);
+    TestInsertDifferentKeys testInsertDifferentKeys(env);
+    TestChurn testChurn(env);
+    for (;;) {
+        for (ureg c = 0; c < IterationsPerLog; c++) {
+            testInsertSameKeys.run();
+            testInsertDifferentKeys.run();
+            testChurn.run();
+        }
+        turf::Trace::Instance.dumpStats();
+
+#if JUNCTION_TRACK_GRAMPA_STATS
+        junction::DefaultQSBR.flush();
+        junction::details::GrampaStats& stats = junction::details::GrampaStats::Instance;
+        printf("---------------------------\n");
+        printf("numTables: %d/%d\n", (int) stats.numTables.current.load(turf::Relaxed), (int) stats.numTables.total.load(turf::Relaxed));
+        printf("numTableMigrations: %d/%d\n", (int) stats.numTableMigrations.current.load(turf::Relaxed), (int) stats.numTableMigrations.total.load(turf::Relaxed));
+        printf("numFlatTrees: %d/%d\n", (int) stats.numFlatTrees.current.load(turf::Relaxed), (int) stats.numFlatTrees.total.load(turf::Relaxed));
+        printf("numFlatTreeMigrations: %d/%d\n", (int) stats.numFlatTreeMigrations.current.load(turf::Relaxed), (int) stats.numFlatTreeMigrations.total.load(turf::Relaxed));
+#endif
+    }
+
+    return 0;
+}
diff --git a/samples/MapCorrectnessTests/TestChurn.h b/samples/MapCorrectnessTests/TestChurn.h
new file mode 100644 (file)
index 0000000..5b93ff4
--- /dev/null
@@ -0,0 +1,173 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef SAMPLES_MAPCORRECTNESSTESTS_TESTCHURN_H
+#define SAMPLES_MAPCORRECTNESSTESTS_TESTCHURN_H
+
+#include <junction/Core.h>
+#include "TestEnvironment.h"
+#include <turf/extra/Random.h>
+#include <vector>
+#include <turf/Util.h>
+
+class TestChurn {
+public:
+    static const ureg KeysInBlock = 32;
+    static const ureg BlocksToMaintain = 256;
+    static const ureg BlocksToLookup = 4;
+    static const ureg StepsPerIteration = 100;
+
+    enum Phase {
+        Phase_Insert,
+        Phase_Lookup,
+        Phase_Erase,
+        Phase_LookupDeleted,
+    };
+
+    struct ThreadInfo {
+        turf::extra::Random random;
+        u32 rangeLo;
+        u32 rangeHi;
+        u32 insertIndex;
+        u32 eraseIndex;
+        u32 lookupIndex;
+        Phase phase;
+        ureg keysToCheck;
+    };
+
+    TestEnvironment& m_env;
+    MapAdapter::Map m_map;
+    u32 m_rangePerThread;
+    u32 m_relativePrime;
+    std::vector<ThreadInfo> m_threads;
+
+    TestChurn(TestEnvironment& env) : m_env(env), m_map(MapAdapter::getInitialCapacity(KeysInBlock * BlocksToMaintain * env.numThreads)) {
+        m_threads.resize(m_env.numThreads);
+        m_rangePerThread = u32(-3) / m_env.numThreads;      // from 2 to 0xffffffff inclusive
+        TURF_ASSERT(KeysInBlock * (BlocksToMaintain + BlocksToLookup + 1) < m_rangePerThread);
+        u32 startIndex = 2;
+        for (ureg i = 0; i < m_env.numThreads; i++) {
+            ThreadInfo& thread = m_threads[i];
+            thread.rangeLo = startIndex;
+            startIndex += m_rangePerThread;
+            thread.rangeHi = startIndex;
+            thread.insertIndex = thread.rangeLo + thread.random.next32() % m_rangePerThread;
+            thread.eraseIndex = thread.insertIndex;
+            thread.lookupIndex = 0;
+            thread.phase = Phase_Insert;
+            thread.keysToCheck = 0;
+        }
+        m_relativePrime = m_threads[0].random.next32() * 2 + 1;
+        m_env.dispatcher.kick(&TestChurn::warmUp, *this);
+    }
+
+    void warmUp(ureg threadIndex) {
+        ThreadInfo& thread = m_threads[threadIndex];
+        TURF_ASSERT(thread.phase == Phase_Insert);
+        TURF_ASSERT(thread.insertIndex == thread.eraseIndex);
+        for (sreg keysRemaining = KeysInBlock * BlocksToMaintain; keysRemaining > 0; keysRemaining--) {
+            u32 key = thread.insertIndex * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {
+                m_map.insert(key, (void*) uptr(key));
+            }
+            if (++thread.insertIndex >= thread.rangeHi)
+                thread.insertIndex = thread.rangeLo;
+        }
+    }
+
+    void doChurn(ureg threadIndex) {
+        ThreadInfo& thread = m_threads[threadIndex];
+        TURF_ASSERT(thread.insertIndex != thread.eraseIndex);
+        for (sreg stepsRemaining = StepsPerIteration; stepsRemaining > 0; stepsRemaining--) {
+            switch (thread.phase) {
+                case Phase_Insert: {
+                    for (sreg keysRemaining = KeysInBlock; keysRemaining > 0; keysRemaining--) {
+                        u32 key = thread.insertIndex * m_relativePrime;
+                        key = key ^ (key >> 16);
+                        if (key >= 2) {
+                            m_map.insert(key, (void*) uptr(key));
+                        }
+                        if (++thread.insertIndex >= thread.rangeHi)
+                            thread.insertIndex = thread.rangeLo;
+                        TURF_ASSERT(thread.insertIndex != thread.eraseIndex);
+                    }
+                    thread.phase = Phase_Lookup;
+                    thread.lookupIndex = thread.insertIndex;
+                    thread.keysToCheck = KeysInBlock + (thread.random.next32() % (KeysInBlock * (BlocksToLookup - 1)));
+                    break;
+                }
+                case Phase_Lookup: {
+                    sreg keysRemaining = turf::util::min(thread.keysToCheck, KeysInBlock);
+                    thread.keysToCheck -= keysRemaining;
+                    for (; keysRemaining > 0; keysRemaining--) {
+                        if (thread.lookupIndex == thread.rangeLo)
+                            thread.lookupIndex = thread.rangeHi;
+                        thread.lookupIndex--;
+                        u32 key = thread.lookupIndex * m_relativePrime;
+                        key = key ^ (key >> 16);
+                        if (key >= 2) {
+                            if (m_map.get(key) != (void*) uptr(key))
+                                TURF_DEBUG_BREAK();
+                        }
+                    }
+                    if (thread.keysToCheck == 0) {
+                        thread.phase = Phase_Erase;
+                    }
+                    break;
+                }
+                case Phase_Erase: {
+                    for (sreg keysRemaining = KeysInBlock; keysRemaining > 0; keysRemaining--) {
+                        u32 key = thread.eraseIndex * m_relativePrime;
+                        key = key ^ (key >> 16);
+                        if (key >= 2) {
+                            m_map.erase(key);
+                        }
+                        if (++thread.eraseIndex >= thread.rangeHi)
+                            thread.eraseIndex = thread.rangeLo;
+                        TURF_ASSERT(thread.insertIndex != thread.eraseIndex);
+                    }
+                    thread.phase = Phase_LookupDeleted;
+                    thread.lookupIndex = thread.eraseIndex;
+                    thread.keysToCheck = KeysInBlock + (thread.random.next32() % (KeysInBlock * (BlocksToLookup - 1)));
+                    break;
+                }
+                case Phase_LookupDeleted: {
+                    sreg keysRemaining = turf::util::min(thread.keysToCheck, KeysInBlock);
+                    thread.keysToCheck -= keysRemaining;
+                    for (; keysRemaining > 0; keysRemaining--) {
+                        if (thread.lookupIndex == thread.rangeLo)
+                            thread.lookupIndex = thread.rangeHi;
+                        thread.lookupIndex--;
+                        u32 key = thread.lookupIndex * m_relativePrime;
+                        key = key ^ (key >> 16);
+                        if (key >= 2) {
+                            if (m_map.get(key))
+                                TURF_DEBUG_BREAK();
+                        }
+                    }
+                    if (thread.keysToCheck == 0) {
+                        thread.phase = Phase_Insert;
+                    }
+                    break;
+                }
+            }
+        }
+        m_env.threads[threadIndex].update();
+    }
+
+    void run() {
+        m_env.dispatcher.kick(&TestChurn::doChurn, *this);
+    }
+};
+
+#endif // SAMPLES_MAPCORRECTNESSTESTS_TESTCHURN_H
diff --git a/samples/MapCorrectnessTests/TestEnvironment.h b/samples/MapCorrectnessTests/TestEnvironment.h
new file mode 100644 (file)
index 0000000..6246272
--- /dev/null
@@ -0,0 +1,43 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef SAMPLES_MAPCORRECTNESSTESTS_TESTENVIRONMENT_H
+#define SAMPLES_MAPCORRECTNESSTESTS_TESTENVIRONMENT_H
+
+#include <junction/Core.h>
+#include <turf/extra/JobDispatcher.h>
+#include <turf/Trace.h>
+#include <junction/extra/MapAdapter.h>
+
+using namespace turf::intTypes;
+typedef junction::extra::MapAdapter MapAdapter;
+
+struct TestEnvironment {
+    turf::extra::JobDispatcher dispatcher;
+    ureg numThreads;
+    MapAdapter adapter;
+    std::vector<MapAdapter::ThreadContext> threads;
+
+    TestEnvironment() : numThreads(dispatcher.getNumPhysicalCores()), adapter(numThreads) {
+        TURF_ASSERT(numThreads > 0);
+        for (ureg t = 0; t < numThreads; t++)
+            threads.emplace_back(adapter, t);
+        dispatcher.kickMulti(&MapAdapter::ThreadContext::registerThread, &threads[0], threads.size());
+    }
+
+    ~TestEnvironment() {
+        dispatcher.kickMulti(&MapAdapter::ThreadContext::unregisterThread, &threads[0], threads.size());
+    }
+};
+
+
+#endif // SAMPLES_MAPCORRECTNESSTESTS_TESTENVIRONMENT_H
diff --git a/samples/MapCorrectnessTests/TestInsertDifferentKeys.h b/samples/MapCorrectnessTests/TestInsertDifferentKeys.h
new file mode 100644 (file)
index 0000000..df21e29
--- /dev/null
@@ -0,0 +1,134 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTDIFFERENTKEYS_H
+#define SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTDIFFERENTKEYS_H
+
+#include <junction/Core.h>
+#include "TestEnvironment.h"
+#include <turf/extra/Random.h>
+
+class TestInsertDifferentKeys {
+public:
+    static const ureg KeysToInsert = 2048;
+    TestEnvironment& m_env;
+    MapAdapter::Map *m_map;
+    turf::extra::Random m_random;
+    u32 m_startIndex;
+    u32 m_relativePrime;
+
+    TestInsertDifferentKeys(TestEnvironment& env) : m_env(env), m_map(NULL), m_startIndex(0), m_relativePrime(0) {
+    }
+
+    void insertKeys(ureg threadIndex) {
+        u32 index = m_startIndex + threadIndex * (KeysToInsert + 2);
+        sreg keysRemaining = KeysToInsert;
+        while (keysRemaining > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                m_map->insert(key, (void*) uptr(key));
+                keysRemaining--;
+            }
+            index++;
+        }
+        m_env.threads[threadIndex].update();
+    }
+
+    void eraseKeys(ureg threadIndex) {
+        u32 index = m_startIndex + threadIndex * (KeysToInsert + 2);
+        sreg keysRemaining = KeysToInsert;
+        while (keysRemaining > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                m_map->erase(key);
+                keysRemaining--;
+            }
+            index++;
+        }
+        m_env.threads[threadIndex].update();
+    }
+
+    void checkMapContents() {
+#if TEST_CHECK_MAP_CONTENTS
+        ureg iterCount = 0;
+        ureg iterChecksum = 0;
+        for (MapAdapter::Map::Iterator iter(*m_map); iter.isValid(); iter.next()) {
+            iterCount++;
+            u32 key = iter.getKey();
+            iterChecksum += key;
+            if (iter.getValue() != (void*) uptr(key))
+                TURF_DEBUG_BREAK();
+        }
+
+        ureg actualChecksum = 0;
+        for (ureg i = 0; i < m_env.numThreads; i++) {
+            u32 index = m_startIndex + i * (KeysToInsert + 2);
+            sreg leftToCheck = KeysToInsert;
+            while (leftToCheck > 0) {
+                u32 key = index * m_relativePrime;
+                key = key ^ (key >> 16);
+                if (key >= 2) {         // Don't insert 0 or 1
+                    if (m_map->get(key) != (void*) uptr(key))
+                        TURF_DEBUG_BREAK();
+                    actualChecksum += key;
+                    leftToCheck--;
+                }
+                index++;
+            }
+        }
+
+        if (iterCount != KeysToInsert * m_env.numThreads)
+            TURF_DEBUG_BREAK();
+        if (iterChecksum != actualChecksum)
+            TURF_DEBUG_BREAK();
+#endif
+    }
+
+    void checkMapEmpty() {
+#if TEST_CHECK_MAP_CONTENTS
+        for (MapAdapter::Map::Iterator iter(*m_map); iter.isValid(); iter.next()) {
+            TURF_DEBUG_BREAK();
+        }
+        
+        for (ureg i = 0; i < m_env.numThreads; i++) {
+            u32 index = m_startIndex + i * (KeysToInsert + 2);
+            sreg leftToCheck = KeysToInsert;
+            while (leftToCheck > 0) {
+                u32 key = index * m_relativePrime;
+                key = key ^ (key >> 16);
+                if (key >= 2) {         // Don't insert 0 or 1
+                    if (m_map->get(key))
+                        TURF_DEBUG_BREAK();
+                    leftToCheck--;
+                }
+                index++;
+            }
+        }
+#endif // TEST_CHECK_MAP_CONTENTS
+    }
+
+    void run() {
+        m_map = new MapAdapter::Map(MapAdapter::getInitialCapacity(KeysToInsert));
+        m_startIndex = m_random.next32();
+        m_relativePrime = m_random.next32() * 2 + 1;
+        m_env.dispatcher.kick(&TestInsertDifferentKeys::insertKeys, *this);
+        checkMapContents();
+        m_env.dispatcher.kick(&TestInsertDifferentKeys::eraseKeys, *this);
+        checkMapEmpty();
+        delete m_map;
+        m_map = NULL;
+    }
+};
+
+#endif // SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTDIFFERENTKEYS_H
diff --git a/samples/MapCorrectnessTests/TestInsertSameKeys.h b/samples/MapCorrectnessTests/TestInsertSameKeys.h
new file mode 100644 (file)
index 0000000..3e696af
--- /dev/null
@@ -0,0 +1,130 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#ifndef SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTSAMEKEYS_H
+#define SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTSAMEKEYS_H
+
+#include <junction/Core.h>
+#include "TestEnvironment.h"
+#include <turf/extra/Random.h>
+
+class TestInsertSameKeys {
+public:
+    static const ureg KeysToInsert = 2048;
+    TestEnvironment& m_env;
+    MapAdapter::Map *m_map;
+    turf::extra::Random m_random;
+    u32 m_startIndex;
+    u32 m_relativePrime;
+
+    TestInsertSameKeys(TestEnvironment& env) : m_env(env), m_map(NULL), m_startIndex(0), m_relativePrime(0) {
+    }
+
+    void insertKeys(ureg threadIndex) {
+        u32 index = m_startIndex;
+        sreg keysRemaining = KeysToInsert;
+        while (keysRemaining > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                m_map->insert(key, (void*) uptr(key));
+                keysRemaining--;
+            }
+            index++;
+        }
+        m_env.threads[threadIndex].update();
+    }
+
+    void eraseKeys(ureg threadIndex) {
+        u32 index = m_startIndex;
+        sreg keysRemaining = KeysToInsert;
+        while (keysRemaining > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                m_map->erase(key);
+                keysRemaining--;
+            }
+            index++;
+        }
+        m_env.threads[threadIndex].update();
+    }
+
+    void checkMapContents() {
+#if TEST_CHECK_MAP_CONTENTS
+        ureg iterCount = 0;
+        ureg iterChecksum = 0;
+        for (MapAdapter::Map::Iterator iter(*m_map); iter.isValid(); iter.next()) {
+            iterCount++;
+            u32 key = iter.getKey();
+            iterChecksum += key;
+            if (iter.getValue() != (void*) uptr(key))
+                TURF_DEBUG_BREAK();
+        }
+
+        ureg actualChecksum = 0;
+        u32 index = m_startIndex;
+        sreg leftToCheck = KeysToInsert;
+        while (leftToCheck > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                if (m_map->get(key) != (void*) uptr(key))
+                    TURF_DEBUG_BREAK();
+                actualChecksum += key;
+                leftToCheck--;
+            }
+            index++;
+        }
+
+        if (iterCount != KeysToInsert)
+            TURF_DEBUG_BREAK();
+        if (iterChecksum != actualChecksum)
+            TURF_DEBUG_BREAK();
+#endif // TEST_CHECK_MAP_CONTENTS
+    }
+
+    void checkMapEmpty() {
+#if TEST_CHECK_MAP_CONTENTS
+        for (MapAdapter::Map::Iterator iter(*m_map); iter.isValid(); iter.next()) {
+            TURF_DEBUG_BREAK();
+        }
+        
+        u32 index = m_startIndex;
+        sreg leftToCheck = KeysToInsert;
+        while (leftToCheck > 0) {
+            u32 key = index * m_relativePrime;
+            key = key ^ (key >> 16);
+            if (key >= 2) {         // Don't insert 0 or 1
+                if (m_map->get(key))
+                    TURF_DEBUG_BREAK();
+                leftToCheck--;
+            }
+            index++;
+        }
+#endif // TEST_CHECK_MAP_CONTENTS
+    }
+
+    void run() {
+        m_map = new MapAdapter::Map(MapAdapter::getInitialCapacity(KeysToInsert));
+        m_startIndex = m_random.next32();
+        m_relativePrime = m_random.next32() * 2 + 1;
+        m_env.dispatcher.kick(&TestInsertSameKeys::insertKeys, *this);
+        checkMapContents();
+        m_env.dispatcher.kick(&TestInsertSameKeys::eraseKeys, *this);
+        checkMapEmpty();
+        delete m_map;
+        m_map = NULL;
+    }
+};
+
+#endif // SAMPLES_MAPCORRECTNESSTESTS_TESTINSERTSAMEKEYS_H
diff --git a/samples/MapCorrectnessTests/junction_userconfig.h.in b/samples/MapCorrectnessTests/junction_userconfig.h.in
new file mode 100644 (file)
index 0000000..3994dab
--- /dev/null
@@ -0,0 +1,4 @@
+#cmakedefine01 TEST_CHECK_MAP_CONTENTS
+
+#define TURF_IMPL_TRACE_PATH "impl/Trace_Counters.h"
+#define TURF_IMPL_TRACE_TYPE turf::Trace_Counters
diff --git a/samples/MapMemoryBench/CMakeLists.txt b/samples/MapMemoryBench/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9838328
--- /dev/null
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 2.8.5)
+
+get_filename_component(SAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    # CMAKE_CONFIGURATION_TYPES only reliable if set before project(), and not from an include file
+    set(CMAKE_CONFIGURATION_TYPES "Debug;RelWithAsserts;RelWithDebInfo" CACHE INTERNAL "Build configs")
+    project(${SAMPLE_NAME})
+endif()    
+
+include(../../cmake/AddSample.cmake)
diff --git a/samples/MapMemoryBench/MapMemoryBench.cpp b/samples/MapMemoryBench/MapMemoryBench.cpp
new file mode 100644 (file)
index 0000000..e0c8fdc
--- /dev/null
@@ -0,0 +1,71 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <turf/Heap.h>
+#include <turf/Util.h>
+#include <stdio.h>
+#include <junction/extra/MapAdapter.h>
+
+#if TURF_USE_DLMALLOC && TURF_DLMALLOC_FAST_STATS
+
+using namespace turf::intTypes;
+typedef junction::extra::MapAdapter MapAdapter;
+
+static const ureg MaxPopulation = 1000000;
+static const ureg MinPopulation = 1000;
+static const ureg StepSize = 500;
+static const u32 Prime = 0x4190ab09;
+
+int main() {
+    MapAdapter adapter(1);
+    MapAdapter::ThreadContext threadCtx(adapter, 0);
+    threadCtx.registerThread();
+
+    ureg startMem = TURF_HEAP.getInUseBytes();
+    ureg mem = 0;
+    ureg initialCapacity = MapAdapter::getInitialCapacity(MaxPopulation);
+    MapAdapter::Map* map = new MapAdapter::Map(initialCapacity);
+
+    printf("[\n");
+    ureg population = 0;
+    while (population < MaxPopulation) {
+        ureg loMem = mem;
+        ureg hiMem = mem;
+        for (ureg target = population + StepSize; population < target; population++) {
+            u32 key = u32(population + 1) * Prime;
+            if (key >= 2) {
+                map->insert(key, (void*) uptr(key));
+                population++;
+                threadCtx.update();
+                ureg inUseBytes = TURF_HEAP.getInUseBytes();
+                mem = inUseBytes - startMem;
+                loMem = turf::util::min(loMem, mem);
+                hiMem = turf::util::max(hiMem, mem);
+            }
+        }
+        printf("    (%d, %d, %d),\n", (int) population, (int) loMem, (int) hiMem);
+    }
+    printf("]\n");
+
+    delete map;
+    return 0;
+}
+
+#else // TURF_USE_DLMALLOC && TURF_DLMALLOC_FAST_STATS
+
+int main() {
+    fprintf(stderr, "Must configure with TURF_USE_DLMALLOC=1 and TURF_DLMALLOC_FAST_STATS=1\n");
+    return 1;
+}
+
+#endif // TURF_USE_DLMALLOC && TURF_DLMALLOC_FAST_STATS
diff --git a/samples/MapMemoryBench/RenderGraphs.py b/samples/MapMemoryBench/RenderGraphs.py
new file mode 100644 (file)
index 0000000..03b05fe
--- /dev/null
@@ -0,0 +1,193 @@
+#!/usr/bin/env python
+import os
+import cairo
+import math
+import glob
+
+
+#---------------------------------------------------
+#  Cairo drawing helpers
+#---------------------------------------------------
+def createScaledFont(family, size, slant=cairo.FONT_SLANT_NORMAL, weight=cairo.FONT_WEIGHT_NORMAL):
+    """ Simple helper function to create a cairo ScaledFont. """
+    face = cairo.ToyFontFace(family, slant, weight)
+    DEFAULT_FONT_OPTIONS = cairo.FontOptions()
+    DEFAULT_FONT_OPTIONS.set_antialias(cairo.ANTIALIAS_SUBPIXEL)
+    return cairo.ScaledFont(face, cairo.Matrix(xx=size, yy=size), cairo.Matrix(), DEFAULT_FONT_OPTIONS)
+
+def fillAlignedText(cr, x, y, scaledFont, text, alignment = 0):
+    """ Draw some aligned text at the specified co-ordinates.
+    alignment = 0: left-justify
+    alignment = 0.5: center
+    alignment = 1: right-justify """
+    ascent, descent = scaledFont.extents()[:2]
+    x_bearing, y_bearing, width, height = scaledFont.text_extents(text)[:4]
+    with Saved(cr):
+        cr.set_scaled_font(scaledFont)
+        cr.move_to(math.floor(x + 0.5 - width * alignment), math.floor(y + 0.5))
+        cr.text_path(text)
+        cr.fill()
+
+class Saved():
+    """ Preserve cairo state inside the scope of a with statement. """
+    def __init__(self, cr):
+        self.cr = cr
+    def __enter__(self):
+        self.cr.save()
+        return self.cr
+    def __exit__(self, type, value, traceback):
+        self.cr.restore()
+
+
+#---------------------------------------------------
+#  AxisAttribs
+#---------------------------------------------------
+class AxisAttribs:
+    """ Describes one axis on the graph. Can be linear or logarithmic. """
+    
+    def __init__(self, size, min, max, step, logarithmic = False, labeler = lambda x: str(int(x + 0.5))):
+        self.size = float(size)
+        self.logarithmic = logarithmic
+        self.labeler = labeler
+        self.toAxis = lambda x: math.log(x) if logarithmic else float(x)
+        self.fromAxis = lambda x: math.exp(x) if logarithmic else float(x)
+        self.min = self.toAxis(min)
+        self.max = self.toAxis(max)
+        self.step = self.toAxis(step)
+
+    def mapAxisValue(self, x):
+        """ Maps x to a point along the axis.
+        x should already have been filtered through self.toAxis(), especially if logarithmic. """
+        return (x - self.min) / (self.max - self.min) * self.size
+    
+    def iterLabels(self):
+        """ Helper to iterate through all the tick marks along the axis. """
+        lo = int(math.floor(self.min / self.step + 1 - 1e-9))
+        hi = int(math.floor(self.max / self.step + 1e-9))
+        for i in xrange(lo, hi + 1):
+            value = i * self.step
+            if self.min == 0 and i == 0:
+                continue
+            yield self.mapAxisValue(value), self.labeler(self.fromAxis(value))
+
+
+#---------------------------------------------------
+#  Graph
+#---------------------------------------------------
+class Curve:
+    def __init__(self, name, points, color):
+        self.name = name
+        self.points = points
+        self.color = color
+        
+class Graph:
+    """ Renders a graph. """
+    
+    def __init__(self, xAttribs, yAttribs):
+        self.xAttribs = xAttribs
+        self.yAttribs = yAttribs
+        self.curves = []
+
+    def addCurve(self, curve):
+        self.curves.append(curve)
+
+    def renderTo(self, fileName):
+        xAttribs = self.xAttribs
+        yAttribs = self.yAttribs
+
+        # Create the image surface and cairo context
+        surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 140 + int(xAttribs.size + 0.5), 65 + int(yAttribs.size + 0.5))
+        cr = cairo.Context(surface)
+        cr.set_source_rgb(1, 1, 1)
+        cr.paint()
+        cr.set_miter_limit(1.414)
+        cr.translate(58, 11 + yAttribs.size)
+
+        # Draw axes
+        labelFont = createScaledFont('Arial', 11)
+        with Saved(cr):
+            cr.set_line_width(1)
+            cr.set_source_rgb(.4, .4, .4)
+
+            # Horizontal axis
+            cr.move_to(0, -0.5)
+            cr.rel_line_to(xAttribs.size + 1, 0)
+            for pos, label in xAttribs.iterLabels():    # Tick marks
+                x = math.floor(pos + 0.5) + 0.5
+                cr.move_to(x, -1)
+                cr.rel_line_to(0, 4)
+            cr.stroke()
+            for pos, label in xAttribs.iterLabels():    # Labels
+                x = math.floor(pos + 0.5)
+                with Saved(cr):
+                    cr.translate(x - 1, 5)
+                    cr.rotate(-math.pi / 4)
+                    fillAlignedText(cr, 0, 6, labelFont, label, 1)
+
+            # Vertical axis
+            cr.move_to(0.5, 0)
+            cr.rel_line_to(0, -yAttribs.size - 0.5)
+            for pos, label in yAttribs.iterLabels():    # Tick marks
+                if label == '0':
+                    continue
+                y = -math.floor(pos + 0.5) - 0.5
+                cr.move_to(1, y)
+                cr.rel_line_to(-4, 0)
+            cr.stroke()
+            for pos, label in yAttribs.iterLabels():    # Labels
+                if label == '0':
+                    continue
+                fillAlignedText(cr, -4, -pos + 4, labelFont, label, 1)
+
+        # Draw curves
+        for curve in self.curves:
+            points = curve.points
+            width = 2.5
+            color = curve.color
+            with Saved(cr):
+                cr.set_line_width(width)
+                cr.set_source_rgba(*color)
+                with Saved(cr):
+                    cr.rectangle(0, 5, xAttribs.size, -yAttribs.size - 15)
+                    cr.clip()
+                    cr.move_to(xAttribs.mapAxisValue(points[0][0]), -yAttribs.mapAxisValue(points[0][1]))
+                    for x, y, yHi in points[1:]:
+                        cr.line_to(xAttribs.mapAxisValue(x) + 0.5, -yAttribs.mapAxisValue(y) - 0.5)
+                    cr.stroke()
+
+                # Label
+                labelFont = createScaledFont('Arial', 11)
+                label = curve.name
+                x, y, yHi = points[-1]
+                fillAlignedText(cr, xAttribs.mapAxisValue(x) + 3, -yAttribs.mapAxisValue(y) + 4, labelFont, label, 0)
+
+        # Draw axis names
+        cr.set_source_rgb(0, 0, 0)
+        axisFont = createScaledFont('Helvetica', 14, weight=cairo.FONT_WEIGHT_BOLD)
+        with Saved(cr):
+            cr.translate(-47, -yAttribs.size / 2.0)
+            cr.rotate(-math.pi / 2)
+            fillAlignedText(cr, 0, 0, axisFont, "Bytes In Use", 0.5)
+        fillAlignedText(cr, xAttribs.size / 2.0, 50, axisFont, "Population", 0.5)
+
+        # Save PNG file
+        surface.write_to_png(fileName)
+
+
+#---------------------------------------------------
+#  main
+#---------------------------------------------------
+graph = Graph(AxisAttribs(600, 0, 1000000, 200000), AxisAttribs(320, 0, 50000000, 10000000))    
+COLORS = [
+    (1, 0, 0),
+    (1, 0.5, 0),
+    (0.5, 0.5, 0),
+    (0, 1, 0),
+    (0, 0.5, 1),
+    (0, 0, 1),
+    (1, 0, 1)
+]
+for i, fn in enumerate(glob.glob('build*/results.txt')):
+    points = eval(open(fn, 'r').read())
+    graph.addCurve(Curve(os.path.split(fn)[0], points, COLORS[i % len(COLORS)]))
+graph.renderTo('out.png')
diff --git a/samples/MapMemoryBench/TestAllMaps.py b/samples/MapMemoryBench/TestAllMaps.py
new file mode 100644 (file)
index 0000000..1dfc5fa
--- /dev/null
@@ -0,0 +1,54 @@
+#!/usr/bin/env python
+import os
+import subprocess
+import sys
+
+# Default CMake command is just 'cmake' but you can override it by setting
+# the CMAKE environment variable:
+CMAKE = os.getenv('CMAKE', 'cmake')
+
+ALL_MAPS = [
+    ('michael', 'junction/extra/impl/MapAdapter_CDS_Michael.h', ['-DJUNCTION_WITH_CDS=1', '-DTURF_WITH_EXCEPTIONS=1']),
+    ('linear', 'junction/extra/impl/MapAdapter_Linear.h', []),
+    ('leapfrog', 'junction/extra/impl/MapAdapter_LeapFrog.h', []),
+    ('grampa', 'junction/extra/impl/MapAdapter_Grampa.h', []),
+    ('stdmap', 'junction/extra/impl/MapAdapter_StdMap.h', []),
+    ('folly', 'junction/extra/impl/MapAdapter_Folly.h', ['-DJUNCTION_WITH_FOLLY=1', '-DTURF_WITH_EXCEPTIONS=1']),
+    ('nbds', 'junction/extra/impl/MapAdapter_NBDS.h', ['-DJUNCTION_WITH_NBDS=1']),
+    ('tbb', 'junction/extra/impl/MapAdapter_TBB.h', ['-DJUNCTION_WITH_TBB=1']),
+    ('tervel', 'junction/extra/impl/MapAdapter_Tervel.h', ['-DJUNCTION_WITH_TERVEL=1']),
+]
+
+# Scan arguments for path to CMakeLists.txt and args to pass through.
+passThroughArgs = []
+pathArgs = []
+for arg in sys.argv[1:]:
+    if arg.startswith('-'):
+        passThroughArgs.append(arg)
+    else:
+        pathArgs.append(arg)
+if len(pathArgs) != 1:
+    sys.stderr.write('You must provide exactly one path argument.\n')
+    exit(1)
+
+listFilePath = os.path.abspath(pathArgs[0])
+for suffix, include, cmakeOpts in ALL_MAPS:
+    subdir = "build-%s" % suffix
+    if not os.path.exists(subdir):
+        os.mkdir(subdir)
+    os.chdir(subdir)
+    print("Configuring in %s..." % subdir)
+    with open('junction_userconfig.h.in', 'w') as f:
+        f.write('#define JUNCTION_IMPL_MAPADAPTER_PATH "%s"\n' % include)
+
+    userConfigCMakePath = os.path.abspath('junction_userconfig.h.in')
+    if os.sep != '/':
+        userConfigCMakePath = userConfigCMakePath.replace(os.sep, '/')
+    if subprocess.call([CMAKE, listFilePath, '-DCMAKE_INSTALL_PREFIX=TestAllMapsInstallFolder', '-DCMAKE_BUILD_TYPE=RelWithDebInfo', '-DTURF_USE_DLMALLOC=1', '-DTURF_DLMALLOC_FAST_STATS=1',
+                       '-DJUNCTION_USERCONFIG=%s' % userConfigCMakePath] + passThroughArgs + cmakeOpts) == 0:
+        subprocess.check_call([CMAKE, '--build', '.', '--target', 'install', '--config', 'RelWithDebInfo'])
+        print('Running in %s...' % subdir)
+        results = subprocess.check_output([os.path.join('TestAllMapsInstallFolder', 'bin', 'MapMemoryBench')])
+        with open('results.txt', 'wb') as f:
+            f.write(results)
+    os.chdir("..")
diff --git a/samples/MapPerformanceTests/CMakeLists.txt b/samples/MapPerformanceTests/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9838328
--- /dev/null
@@ -0,0 +1,10 @@
+cmake_minimum_required(VERSION 2.8.5)
+
+get_filename_component(SAMPLE_NAME ${CMAKE_CURRENT_SOURCE_DIR} NAME)
+if(CMAKE_SOURCE_DIR STREQUAL CMAKE_CURRENT_SOURCE_DIR)
+    # CMAKE_CONFIGURATION_TYPES only reliable if set before project(), and not from an include file
+    set(CMAKE_CONFIGURATION_TYPES "Debug;RelWithAsserts;RelWithDebInfo" CACHE INTERNAL "Build configs")
+    project(${SAMPLE_NAME})
+endif()    
+
+include(../../cmake/AddSample.cmake)
diff --git a/samples/MapPerformanceTests/MapPerformanceTests.cpp b/samples/MapPerformanceTests/MapPerformanceTests.cpp
new file mode 100644 (file)
index 0000000..4c9b91e
--- /dev/null
@@ -0,0 +1,301 @@
+/*------------------------------------------------------------------------
+  Junction: Concurrent data structures in C++
+  Copyright (c) 2016 Jeff Preshing
+
+  Distributed under the Simplified BSD License.
+  Original location: https://github.com/preshing/junction
+
+  This software is distributed WITHOUT ANY WARRANTY; without even the
+  implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+  See the LICENSE file for more information.
+------------------------------------------------------------------------*/
+
+#include <junction/Core.h>
+#include <turf/CPUTimer.h>
+#include <turf/Util.h>
+#include <turf/extra/UniqueSequence.h>
+#include <turf/extra/JobDispatcher.h>
+#include <junction/Averager.h>
+#include <turf/extra/Options.h>
+#include <junction/extra/MapAdapter.h>
+
+using namespace turf::intTypes;
+typedef junction::extra::MapAdapter MapAdapter;
+
+static const ureg NumKeysPerThread = 16384;
+static const ureg DefaultReadsPerWrite = 19;
+static const ureg DefaultItersPerChunk = 128;
+static const ureg DefaultChunks = 10;
+static const u32 Prime = 0x4190ab09;
+
+class Delay {
+private:
+    turf::extra::Random m_rand;
+    u32 m_threshold;
+
+public:
+    Delay(float ratio) {
+        m_threshold = u32(double(0xffffffffu) * ratio);
+    }
+
+    void delay(ureg& workUnits) {
+        for (;;) {
+            volatile ureg v = m_rand.next32();
+            workUnits++;
+            if (v <= m_threshold)
+                break;
+        }
+    }
+};
+
+struct SharedState {
+    MapAdapter& adapter;
+    MapAdapter::Map* map;
+    ureg numKeysPerThread;
+    float delayFactor;
+    ureg numThreads;
+    ureg readsPerWrite;
+    ureg itersPerChunk;
+    turf::extra::SpinKicker spinKicker;
+    turf::Atomic<u32> doneFlag;
+
+    SharedState(MapAdapter& adapter, ureg numThreads, ureg numKeysPerThread, ureg readsPerWrite, ureg itersPerChunk)
+        : adapter(adapter), map(NULL), numKeysPerThread(numKeysPerThread), numThreads(numThreads), readsPerWrite(readsPerWrite), itersPerChunk(itersPerChunk) {
+        delayFactor = 0.5f;
+        doneFlag.storeNonatomic(0);
+    }
+};
+
+class ThreadState {
+public:
+    SharedState& m_shared;
+    MapAdapter::ThreadContext m_threadCtx;
+    ureg m_threadIndex;
+    u32 m_rangeLo;
+    u32 m_rangeHi;
+
+    u32 m_addIndex;
+    u32 m_removeIndex;
+
+    struct Stats {
+        ureg workUnitsDone;
+        ureg mapOpsDone;
+        double duration;
+
+        Stats() {
+            workUnitsDone = 0;
+            mapOpsDone = 0;
+            duration = 0;
+        }
+
+        Stats& operator+=(const Stats& other) {
+            workUnitsDone += other.workUnitsDone;
+            mapOpsDone += other.mapOpsDone;
+            duration += other.duration;
+            return *this;
+        }
+
+        bool operator<(const Stats& other) const {
+            return duration < other.duration;
+        }
+    };
+
+    Stats m_stats;
+
+    ThreadState(SharedState& shared, ureg threadIndex, u32 rangeLo, u32 rangeHi) : m_shared(shared), m_threadCtx(shared.adapter, threadIndex) {
+        m_threadIndex = threadIndex;
+        m_rangeLo = rangeLo;
+        m_rangeHi = rangeHi;
+        m_addIndex = rangeLo;
+        m_removeIndex = rangeLo;
+    }
+
+    void registerThread() {
+        m_threadCtx.registerThread();
+    }
+
+    void unregisterThread() {
+        m_threadCtx.unregisterThread();
+    }
+
+    void initialPopulate() {
+        TURF_ASSERT(m_addIndex == m_removeIndex);
+        MapAdapter::Map *map = m_shared.map;
+        for (ureg i = 0; i < m_shared.numKeysPerThread; i++) {
+            u32 key = m_addIndex * Prime;
+            map->insert(key, (void*) (key & ~uptr(3)));
+            if (++m_addIndex == m_rangeHi)
+                m_addIndex = m_rangeLo;
+        }
+    }
+
+    void run() {
+        MapAdapter::Map *map = m_shared.map;
+        turf::CPUTimer::Converter converter;
+        Delay delay(m_shared.delayFactor);
+        Stats stats;
+        ureg lookupIndex = m_rangeLo;
+        ureg remaining = m_shared.itersPerChunk;
+        if (m_threadIndex == 0)
+            m_shared.spinKicker.kick(m_shared.numThreads - 1);
+        else {
+            remaining = ~u32(0);
+            m_shared.spinKicker.waitForKick();
+        }
+
+        // ---------
+        turf::CPUTimer::Point start = turf::CPUTimer::get();
+        for (; remaining > 0; remaining--) {
+            // Add
+            delay.delay(stats.workUnitsDone);
+            if (m_shared.doneFlag.load(turf::Relaxed))
+                break;
+            u32 key = m_addIndex * Prime;
+            if (key >= 2) {
+                map->insert(key, (void*) uptr(key));
+                stats.mapOpsDone++;
+            }
+            if (++m_addIndex == m_rangeHi)
+                m_addIndex = m_rangeLo;
+
+            // Lookup
+            if (s32(lookupIndex - m_removeIndex) < 0)
+                lookupIndex = m_removeIndex;
+            for (ureg l = 0; l < m_shared.readsPerWrite; l++) {
+                delay.delay(stats.workUnitsDone);
+                if (m_shared.doneFlag.load(turf::Relaxed))
+                    break;
+                key = lookupIndex * Prime;
+                if (key >= 2) {
+                    volatile void* value = map->get(key);
+                    TURF_UNUSED(value);
+                    stats.mapOpsDone++;
+                }
+                if (++lookupIndex == m_rangeHi)
+                    lookupIndex = m_rangeLo;
+                if (lookupIndex == m_addIndex)
+                    lookupIndex = m_removeIndex;
+            }
+
+            // Remove
+            delay.delay(stats.workUnitsDone);
+            if (m_shared.doneFlag.load(turf::Relaxed))
+                break;
+            key = m_removeIndex * Prime;
+            if (key >= 2) {
+                map->erase(key);
+                stats.mapOpsDone++;
+            }
+            if (++m_removeIndex == m_rangeHi)
+                m_removeIndex = m_rangeLo;
+
+            // Lookup
+            if (s32(lookupIndex - m_removeIndex) < 0)
+                lookupIndex = m_removeIndex;
+            for (ureg l = 0; l < m_shared.readsPerWrite; l++) {
+                delay.delay(stats.workUnitsDone);
+                if (m_shared.doneFlag.load(turf::Relaxed))
+                    break;
+                key = lookupIndex * Prime;
+                if (key >= 2) {
+                    volatile void* value = map->get(key);
+                    TURF_UNUSED(value);
+                    stats.mapOpsDone++;
+                }
+                if (++lookupIndex == m_rangeHi)
+                    lookupIndex = m_rangeLo;
+                if (lookupIndex == m_addIndex)
+                    lookupIndex = m_removeIndex;
+            }
+        }
+        if (m_threadIndex == 0)
+            m_shared.doneFlag.store(1, turf::Relaxed);
+        m_threadCtx.update();
+        turf::CPUTimer::Point end = turf::CPUTimer::get();
+        // ---------
+
+        stats.duration = converter.toSeconds(end - start);
+        m_stats = stats;
+    }
+};
+
+static const turf::extra::Option Options[] = {
+    { "readsPerWrite", 'r', true, "number of reads per write" },
+    { "itersPerChunk", 'i', true, "number of iterations per chunk" },
+    { "chunks", 'c', true, "number of chunks to execute" },
+    { "keepChunkFraction", 'k', true, "threshold fraction of chunk timings to keep" },
+};
+
+int main(int argc, const char** argv) {
+    turf::extra::Options options(Options, TURF_STATIC_ARRAY_SIZE(Options));
+    options.parse(argc, argv);
+    ureg readsPerWrite = options.getInteger("readsPerWrite", DefaultReadsPerWrite);
+    ureg itersPerChunk = options.getInteger("itersPerChunk", DefaultItersPerChunk);
+    ureg chunks = options.getInteger("chunks", DefaultChunks);
+    double keepChunkFraction = options.getDouble("keepChunkFraction", 1.0);
+
+    turf::extra::JobDispatcher dispatcher;
+    ureg numThreads = dispatcher.getNumPhysicalCores();
+    MapAdapter adapter(numThreads);
+
+    // Create shared state and register threads
+    SharedState shared(adapter, numThreads, NumKeysPerThread, readsPerWrite, itersPerChunk);
+    std::vector<ThreadState> threads;
+    threads.reserve(numThreads);
+    for (ureg t = 0; t < numThreads; t++) {
+        u32 rangeLo = 0xffffffffu / numThreads * t + 1;
+        u32 rangeHi = 0xffffffffu / numThreads * (t + 1) + 1;
+        threads.emplace_back(shared, t, rangeLo, rangeHi);
+    }
+    dispatcher.kickMulti(&ThreadState::registerThread, &threads[0], threads.size());
+
+    {
+        // Create the map
+        MapAdapter::Map map(MapAdapter::getInitialCapacity(numThreads * NumKeysPerThread));
+        shared.map = &map;
+        dispatcher.kickMulti(&ThreadState::initialPopulate, &threads[0], threads.size());
+
+        printf("{\n");
+        printf("'mapType': '%s',\n", MapAdapter::MapName);
+        printf("'readsPerWrite': %d,\n", (int) readsPerWrite);
+        printf("'itersPerChunk': %d,\n", (int) itersPerChunk);
+        printf("'chunks': %d,\n", (int) chunks);
+        printf("'keepChunkFraction': %f,\n", keepChunkFraction);
+        printf("'labels': ('delayFactor', 'workUnitsDone', 'mapOpsDone', 'totalTime'),\n"),
+        printf("'points': [\n");
+        for (float delayFactor = 1.f; delayFactor >= 0.0005f; delayFactor *= 0.95f)
+        {
+            shared.delayFactor = delayFactor;
+
+            std::vector<ThreadState::Stats> kickTotals;
+            for (ureg c = 0; c < chunks; c++) {
+                shared.doneFlag.storeNonatomic(false);
+                dispatcher.kickMulti(&ThreadState::run, &threads[0],&nb