Concurrent Word Search in Go Using Goroutines

2 min read .

We will explore a Go program that demonstrates how to perform concurrent searches for a word within multiple texts using goroutines. This approach leverages Go’s concurrency features to efficiently handle search operations across multiple texts.

Overview

The Go program provided performs the following tasks:

  1. Searches for a word in individual texts: The searchInText function checks if a specified word is present in a given text.
  2. Searches across multiple texts concurrently: The searchWordInTexts function uses goroutines to search for the word in multiple texts simultaneously.
  3. Prints the result: The main function initializes the texts and word to be searched, and outputs whether the word was found or not.

The Code

Here is the Go code with detailed explanations:

package main

import (
	"fmt"
	"strings"
	"sync"
)

// searchInText is a function that searches for a word in a given text and returns the result.
func searchInText(text, word string) bool {
	if text == "" || word == "" {
		return false
	}
	// Convert both text and word to lowercase for case-insensitive comparison
	text = strings.ToLower(text)
	word = strings.ToLower(word)
	return strings.Contains(text, word)
}

// searchWordInTexts is a function that searches for a word in an array of texts concurrently.
func searchWordInTexts(texts []string, word string) bool {
	var wg sync.WaitGroup
	var mu sync.Mutex
	found := false

	for _, text := range texts {
		wg.Add(1)
		go func(t string) {
			defer wg.Done()
			if searchInText(t, word) {
				mu.Lock()
				found = true
				mu.Unlock()
			}
		}(text)
	}

	wg.Wait()
	return found
}

func main() {
	texts := []string{
		"This is a long example text",
		"Another text for word searching",
		"This program uses goroutines for searching",
	}
	word := "program"

	if searchWordInTexts(texts, word) {
		fmt.Printf("The word '%s' was found in the texts\n", word)
	} else {
		fmt.Printf("The word '%s' was not found in the texts\n", word)
	}
}

Explanation

  1. searchInText Function:

    • Converts both the text and the word to lowercase to ensure a case-insensitive search.
    • Uses strings.Contains to check if the word is present in the text.
  2. searchWordInTexts Function:

    • Utilizes sync.WaitGroup to wait for all goroutines to finish their execution.
    • Uses sync.Mutex to synchronize access to the shared variable found, which indicates whether the word was found in any of the texts.
    • Launches a new goroutine for each text to perform the search concurrently.
  3. main Function:

    • Initializes a slice of texts and the word to search for.
    • Calls searchWordInTexts to perform the concurrent search.
    • Prints whether the word was found or not based on the result of the search.

Conclusion

This Go program demonstrates how to efficiently search for a word across multiple texts using concurrent programming. By leveraging goroutines and synchronization primitives like sync.Mutex and sync.WaitGroup, the program performs searches in parallel, which can significantly speed up the process when dealing with large volumes of text. This approach is particularly useful in scenarios where performance is critical and tasks can be performed concurrently.

Tags:
Golang

See Also

chevron-up