Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WaitGroup can't wake up randomly #900

Open
cpunion opened this issue Dec 3, 2024 · 1 comment
Open

WaitGroup can't wake up randomly #900

cpunion opened this issue Dec 3, 2024 · 1 comment
Labels
duplicate This issue or pull request already exists

Comments

@cpunion
Copy link
Contributor

cpunion commented Dec 3, 2024

package main

import (
	"fmt"
	"sync"
	"time"

	"github.com/goplus/llgo/c"
)

func timeout(d time.Duration) <-chan struct{} {
	ch := make(chan struct{})
	go func() {
		c.Usleep(c.Uint(d.Microseconds()))
		close(ch)
	}()
	return ch
}

func main() {
	ch := make(chan int)
	var wg sync.WaitGroup

	// Start a receiver goroutine
	go func() {
		for i := 0; i < 2; i++ {
			select {
			case v := <-ch:
				fmt.Printf("Received: %d\n", v)
			case <-timeout(time.Second):
				fmt.Println("Receive timeout")
			}
		}
	}()

	for i := 0; i < 2; i++ {
		wg.Add(1)
		go func(id int) {
			defer 
			select {
			case ch <- id:
				defer fmt.Printf("Sent value: %d\n", id)
			case <-timeout(time.Millisecond * 100):
				defer fmt.Printf("Timeout for: %d\n", id)
			}
wg.Done()
		}(i)
	}

	wg.Wait()
	close(ch) // Close the channel after all goroutines are done
}
@cpunion cpunion changed the title WaitGroup can't wake up WaitGroup can't wake up randomly Dec 3, 2024
@xushiwei
Copy link
Member

xushiwei commented Jan 9, 2025

Same as #694

@xushiwei xushiwei added the duplicate This issue or pull request already exists label Jan 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
duplicate This issue or pull request already exists
Projects
None yet
Development

No branches or pull requests

2 participants