Go Concurrency with C Performance via CGO
This advanced program demonstrates how Go leverages C's performance and existing libraries while using Go's superior concurrency model through CGO (C-Go) integration.
/**
* Advanced Tier: Go + C Integration (CGO)
* This program demonstrates Go calling C code via CGO
* Use case: Leveraging existing C libraries with Go's concurrency
*/
package main
/*
#include <stdlib.h>
#include <math.h>
// C function: Fast prime number checking
int is_prime_c(long long n) {
if (n < 2) return 0;
if (n == 2) return 1;
if (n % 2 == 0) return 0;
long long sqrt_n = (long long)sqrt((double)n);
for (long long i = 3; i <= sqrt_n; i += 2) {
if (n % i == 0) return 0;
}
return 1;
}
// C function: Array sum (SIMD-style optimization possible)
double array_sum_c(double* arr, int size) {
double sum = 0.0;
for (int i = 0; i < size; i++) {
sum += arr[i];
}
return sum;
}
*/
import "C"
import (
"fmt"
"sync"
"time"
)
// Go wrapper for C prime checking
func isPrimeC(n int64) bool {
return C.is_prime_c(C.longlong(n)) == 1
}
// Go native implementation for comparison
func isPrimeGo(n int64) bool {
if n < 2 {
return false
}
if n == 2 {
return true
}
if n%2 == 0 {
return false
}
for i := int64(3); i*i <= n; i += 2 {
if n%i == 0 {
return false
}
}
return true
}
// Run parallel prime checking (Go concurrency + C computation)
func parallelPrimeCheck(numbers []int64) []bool {
results := make([]bool, len(numbers))
var wg sync.WaitGroup
// Use Go's goroutines with C's computation
for i, num := range numbers {
wg.Add(1)
go func(idx int, n int64) {
defer wg.Done()
results[idx] = isPrimeC(n) // C function called from goroutine
}(i, num)
}
wg.Wait()
return results
}
func main() {
fmt.Println("=" + strings.Repeat("=", 59))
fmt.Println("🐹 + 🔧 GO + C INTEGRATION (CGO)")
fmt.Println("Advanced Tier: Go Concurrency with C Performance")
fmt.Println("=" + strings.Repeat("=", 59))
// Demonstrate Go concurrency with C computation
numbersToCheck := []int64{
1000000007, 1000000009, 1000000021, 1000000033,
}
start := time.Now()
results := parallelPrimeCheck(numbersToCheck)
duration := time.Since(start)
fmt.Printf("Checked %d numbers in parallel: %v\n",
len(numbersToCheck), duration)
for i, num := range numbersToCheck {
fmt.Printf(" %d: %v\n", num, results[i])
}
fmt.Println("\n✨ Languages Used:")
fmt.Println(" 🐹 Go - Concurrency, memory management")
fmt.Println(" 🔧 C - Performance, existing libraries")
fmt.Println(" 🔗 CGO - Bridge between Go and C")
}
Go's safety with C's system-level access for OS operations
Modern Go applications using battle-tested C libraries
Go for orchestration, C for CPU-intensive algorithms
Go's concurrency with C's hardware access and drivers