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

sync: C.pthread_cond_t #22554

Closed
wants to merge 3 commits into from
Closed

Conversation

enghitalo
Copy link
Contributor

fn main() {
	mut queue := new_queue[int]()

	// Start producer and consumer threads
	producer_thread := spawn producer(mut queue)
	consumer_thread := spawn consumer(mut queue)

	// Wait for threads to complete
	producer_thread.wait()
	consumer_thread.wait()

	// Clean up
	queue.destroy()
}

@spytheman
Copy link
Member

Why not just use a channel?

@enghitalo
Copy link
Contributor Author

enghitalo commented Oct 17, 2024

Why not just use a channel?

How can I make the consumer always listen for changes on the channel?

Like here

fn consumer(mut queue ThreadSafeQueue[int]) {
// infinity for loop
	for {
		item := queue.dequeue()
		println('Consumed: ${item}')
	}
}

@enghitalo enghitalo closed this Oct 17, 2024
@enghitalo
Copy link
Contributor Author

It is a better example

import time

fn producer(ch chan int) {
	for i in 1 .. 100 {
		ch <- i
		println('Produced: ${i}')
	}
}

fn consumer(ch chan int) {
	for {
		select {
			item := <-ch {
				println('Consumed: ${item}')
			}

			500 * time.millisecond {
				println('Timeout: No producers were ready within 0.5s')
				break
			}
		}
	}
}

fn main() {
	ch := chan int{cap: 10}

	producer_thread := spawn producer(ch)
	consumer_thread := spawn consumer(ch)

	producer_thread.wait()
	consumer_thread.wait()
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants