Free AI web copilot to create summaries, insights and extended knowledge, download it at here
3474
Abstract
w <code>SafeMap</code>.</li></ul><h1 id="f98e">Step 4: Set Method</h1><p id="a46c">Now, let’s create a method to set key-value pairs in our map. Add this code to the <code>SafeMap</code> struct:</p><div id="3d52"><pre><span class="hljs-comment">// Set sets a key-value pair in the map.</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(m *SafeMap)</span></span> Set(key <span class="hljs-type">string</span>, value <span class="hljs-type">int</span>) {
m.mu.Lock()
<span class="hljs-keyword">defer</span> m.mu.Unlock()
m.data[key] = value
}</pre></div><ul><li>We define a method called <code>Set</code> that takes a key and a value as parameters.</li><li><code>m.mu.Lock()</code> locks the mutex to ensure exclusive access to the map.</li><li>We use <code>defer</code> to ensure that the mutex is unlocked even if an error occurs or the function returns.</li><li>Finally, we set the key-value pair in the map.</li></ul><h1 id="a568">Step 5: Get Method</h1><p id="cefd">Let’s create a method to retrieve values based on keys. Add this code:</p><div id="2071"><pre><span class="hljs-comment">// Get retrieves the value associated with a key.</span>
<span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-params">(m *SafeMap)</span></span> Get(key <span class="hljs-type">string</span>) (<span class="hljs-type">int</span>, <span class="hljs-type">bool</span>) {
m.mu.Lock()
<span class="hljs-keyword">defer</span> m.mu.Unlock()
val, ok := m.data[key]
<span class="hljs-keyword">return</span> val, ok
}</pre></div><ul><li>We define a method called <code>Get</code> that takes a key as a parameter and returns both the value and a boolean indicating if the key exists.</li><li>We lock the mutex, retrieve the value from the map, and unlock the mutex before returning the result.</li></ul><h1 id="9e28">Step 6: Delete Method</h1><p id="1411">To delete key-value pairs, add the following code:</p><div id="569d"><pre><span class="hljs-comment">// Delete removes a key-value pair from the map.</span>
func (m *SafeMap) <span class="hljs-built_in">Delete</span>(key string) {
m<span class="hljs-selector-class">.mu</span><span class="hljs-selector-class">.Lock</span>()
defer m<span class="hljs-selector-class">.mu</span><span class="hljs-selector-class">.Unlock</span>()
<span class="hljs-built_in">delete</span>(m.data, key)
}</pre></div><ul><li>We define a method called <code>Delete</code> that removes a key-value pair based on the provided key.</li><li>Similar to other methods, we lock the mutex, perform the deletion, and unlock the mutex.</li></ul><h1 id="e8e5">Step 7: Size Method</h1><p id="13e9">Let’s create a method to determine the size of the map:</p><div id="f476"><pre><span class="hljs-comment">// Size returns the number of key-value pairs in the map.</span>
func (m *SafeMap) <span class="hljs-built_in">Size</span>() int {
m<span class="hljs-selector-class">.mu</span><span class="hljs-selector-class">.Lock</span>()
defer m<span class="hljs-selector-class">.mu</span><span class="hljs-selector-class">.Unlock</span>()
return <span class="hljs-built_in">len</span>(m.data)
}</pre></div><ul><li>We define a method called <code>Size</code> that returns the number of key-value pairs in the map.</li><li>As with other methods, we lock the mutex, obtain the size, and unlock the mutex.</li></ul><h1 id="4996">Step 8: Putting It All Together</h1><p id="4eee">Now that we’v
Options
e defined our custom thread-safe map, let’s put it to use:</p><div id="327a"><pre><span class="hljs-function"><span class="hljs-keyword">func</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
<span class="hljs-comment">// Create a new thread-safe map.</span>
safeMap := NewSafeMap()
<span class="hljs-comment">// Set key-value pairs concurrently.</span>
wg := sync.WaitGroup{}
<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; i++ {
wg.Add(<span class="hljs-number">1</span>)
<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-type">int</span>)</span></span> {
<span class="hljs-keyword">defer</span> wg.Done()
key := fmt.Sprintf(<span class="hljs-string">"key%d"</span>, i)
safeMap.Set(key, i)
}(i)
}
wg.Wait()
<span class="hljs-comment">// Get and print values concurrently.</span>
<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i < <span class="hljs-number">100</span>; i++ {
wg.Add(<span class="hljs-number">1</span>)
<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-type">int</span>)</span></span> {
<span class="hljs-keyword">defer</span> wg.Done()
key := fmt.Sprintf(<span class="hljs-string">"key%d"</span>, i)
val, ok := safeMap.Get(key)
<span class="hljs-keyword">if</span> ok {
fmt.Printf(<span class="hljs-string">"Key: %s, Value: %d\n"</span>, key, val)
} <span class="hljs-keyword">else</span> {
fmt.Printf(<span class="hljs-string">"Key: %s not found\n"</span>, key)
}
}(i)
}
wg.Wait()
<span class="hljs-comment">// Delete keys concurrently.</span>
<span class="hljs-keyword">for</span> i := <span class="hljs-number">0</span>; i < <span class="hljs-number">50</span>; i++ {
wg.Add(<span class="hljs-number">1</span>)
<span class="hljs-keyword">go</span> <span class="hljs-function"><span class="hljs-keyword">func</span><span class="hljs-params">(i <span class="hljs-type">int</span>)</span></span> {
<span class="hljs-keyword">defer</span> wg.Done()
key := fmt.Sprintf(<span class="hljs-string">"key%d"</span>, i)
safeMap.Delete(key)
}(i)
}
wg.Wait()
<span class="hljs-comment">// Print the final size of the map.</span>
size := safeMap.Size()
fmt.Printf(<span class="hljs-string">"Map size: %d\n"</span>, size)
}</pre></div><ul><li>In the <code>main</code> function, we create an instance of our <code>SafeMap</code>.</li><li>We set key-value pairs concurrently using goroutines.</li><li>We retrieve and print values concurrently.</li><li>We delete keys concurrently.</li><li>Finally, we print the size of the map.</li></ul><h1 id="d1df">Conclusion</h1><p id="c100">You’ve just created a custom thread-safe map in Go! This example demonstrates the basics of using mutexes to protect concurrent access to data structures. Understanding these concepts is crucial for building reliable concurrent programs in Go.</p><p id="2e1d">Feel free to explore my repository at <a href="https://github.com/parv-jain/thread-safe-data-structures">https://github.com/parv-jain/thread-safe-data-structures</a> where I plan to delve deeper into and experiment with the implementation of thread-safe data structures in Go.</p></article></body>