To implement a concurrent linked list using synchronization in Go, you can leverage the built-in sync
package for providing mutual exclusion (mutex) to protect the shared data. Below is an example of how you can implement a concurrent linked list:
package main
import (
"fmt"
"sync"
)
type Node struct {
value int
next *Node
}
type LinkedList struct {
head *Node
lock sync.Mutex
}
func (l *LinkedList) Add(value int) {
l.lock.Lock()
defer l.lock.Unlock()
if l.head == nil {
l.head = &Node{value: value}
} else {
current := l.head
for current.next != nil {
current = current.next
}
current.next = &Node{value: value}
}
}
func (l *LinkedList) Display() {
l.lock.Lock()
defer l.lock.Unlock()
if l.head == nil {
fmt.Println("Linked List is empty")
return
}
current := l.head
fmt.Print("LinkedList: ")
for current != nil {
fmt.Printf("%d -> ", current.value)
current = current.next
}
fmt.Println("nil")
}
func main() {
list := LinkedList{}
wg := sync.WaitGroup{}
wg.Add(2)
go func() {
defer wg.Done()
for i := 1; i <= 5; i++ {
list.Add(i)
}
}()
go func() {
defer wg.Done()
for i := 6; i <= 10; i++ {
list.Add(i)
}
}()
wg.Wait()
list.Display()
}
In this example, the LinkedList
struct contains the head
pointer of the linked list and a sync.Mutex
for protecting the concurrent access to the shared data. The Add
method adds a new node to the end of the linked list by acquiring the lock, and the Display
method displays the elements of the list by acquiring the lock as well.
To test the concurrent behavior, two goroutines are created to add elements concurrently to the same linked list. The sync.WaitGroup
is used to wait for both goroutines to finish before displaying the linked list's contents.
Note: Although this implementation provides mutual exclusion to ensure the consistency of shared data, it doesn't handle other synchronization aspects like atomicity or visibility of operations. For more advanced concurrency scenarios, you might need to use additional synchronization primitives or consider other data structures suited for concurrent access.