添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接

C++ 和 Go 语言实现两个线程交替打印数字 1-10

  • C ++ 实现
#include <iostream>
#include <thread>
#include <condition_variable>
#include <mutex>
using namespace std;
mutex mut;  // 定义互斥量
condition_variable cond1, cond2;  // 定义两个条件变量,不同线程等待不同的条件变量
int num = 1;
void thread1() {
	while (num <= 10) {
		unique_lock<mutex> locker(mut); // 使用 unique_lock 锁管理类,自动上锁和解锁
		cout << "thread1: " << num << endl;
		num++;
		cond2.notify_one(); // 线程 1 打印完成,通知线程 2 打印
		cond1.wait(locker); // 等待线程 2 打印完成再继续打印
void thread2() {
	while (num <= 10) {
		unique_lock<mutex> locker(mut);
		cout << "thread2: " << num << endl;
		num++;
		cond1.notify_one();
		cond2.wait(locker);
int main() {
	thread t1(thread1);  // 定义两个线程
	thread t2(thread2);
	t1.join();  // 回收线程资源
	t2.join();
	system("pause");
	return 0;

思路:两个线程分别使用两个不同的条件变量控制,共同等待用一个互斥量,从而实现交替打印的效果

  • Go 实现 1
package main
import (
	"fmt"
	"sync"
const (
	MAX     = 10 // 最大打印到多少
	GoCount = 2   // 同时执行的线程数
func main() {
	fmt.Println(Solution(MAX, GoCount))
func Solution(MAX int, GoCount int) []int {
	wg := sync.WaitGroup{}
	wg.Add(GoCount)
	res := make([]int, 0)
	count := 1
	for i := 0; i < GoCount; i++ {
		go func(k int) { // 注意需要传递参数到协程内
			for {
				now := count
				if now > MAX {
					wg.Done()
					return
				// 这条语句保证任务均匀地分配到所有的协程
			    // now 是当前的任务编号,GoCount 是协程的数量,k 是当前协程的编号。
				if now%GoCount == k {
					res = append(res, now)
					count++
	wg.Wait()
	return res
  • Go 实现 2
package main
import (
    "fmt"
    "sync"
func main() {
    var wg sync.WaitGroup
    wg.Add(2)
    ch1 := make(chan bool)
    ch2 := make(chan bool)
    go func() {
        count := 1
        for count < 10 {
            fmt.Println("groutine 1: ", count)
            count = count + 2
            ch2 <- true
        wg.Done()
    go func() {
        count := 2
        for count <= 10 {
            fmt.Println("groutine 2: ", count)
            count = count + 2
            if count <= 10 {
                ch1 <- true
        wg.Done()
    ch1 <- true
    wg.Wait()

思路:两个 channel 分别控制两个协程,两个 count 计数避免资源竞争

全部评论
空 还没有回复哦~

相关推荐

点赞 评论 收藏
分享
昨天 13:51
莉莉丝游戏_系统工程师(准入职员工)
1)简单的自我介绍2)共享屏幕看了下两个项目,介绍下是为什么要做,然后亮点功能的业务流程3)TypeScript&nbsp;原理实现,转&nbsp;JS4)前后端怎么部署的,怎么上线5)Redis&nbsp;排行榜,数据结构6)Redis&nbsp;数据库和缓存一致性问题7)Redis&nbsp;限流8)缓存击穿9)缓存雪崩10)死锁11)分布式死锁12)信号量13)信号量和互斥锁区别和联系14)并发项目优化点15)SpringMVC&nbsp;模型16)平时喜欢玩游戏吗?17)反问技术栈和业务,面试轮次莉莉丝游戏系统工程师的面经主要包括以下几个环节:‌自我介绍:‌简要介绍个人背景、‌技能及项目经验。‌项目介绍:‌深入介绍个人参与的项目,‌包括项目目的、‌亮点功能的业务流程等。‌技术考察:‌编程语言与原理:‌如TypeScript的原理及与JavaScript的转换。‌前后端部署与上线流程。‌Redis相关:‌如排行榜实现、‌数据库与缓存一致性问题、‌限流、‌缓存击穿与雪崩TCL米哈游等。‌并发项目优化点。‌游戏相关:‌询问平时是否喜欢玩游戏,‌以及相关的游戏体验或理解。‌反问环节:‌了解技术栈、‌业务及面试流程等。‌【内推链接】https://lilithgames.jobs.feishu.cn/s/ir83CLDU【内推码】UWMZ21P(选择校园大使内推,免hr筛选)投递的UU留下姓名缩写+岗位~我会尽力跟进~
莉莉丝游戏
|
校招
|
31个岗位
点赞 评论 收藏
分享
3 17 评论
分享

全站热榜