AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / 问题

Perguntas[go](coding)

Martin Hope
Mahsa Fathi
Asked: 2025-04-28 19:15:05 +0800 CST

Loop infinito ao usar o comando redis scan para excluir padrões em golang

  • 6

Estou usando o comando scan em golang para obter chaves do Redis por meio de um padrão fornecido. Estou usando um cluster do Redis e, portanto, para evitar chaves perdidas, uso o ForEachMaster. Este é o código que uso:

func deleteCacheKeys(ctx context.Context, pattern string, count int64, retries int) error {
    redisClient := redis.NewClusterClient(&redis.ClusterOptions{
        Addrs: []string{redisCluster},
    })
    if err := redisClient.Ping(ctx).Err(); err != nil {
        return err
    }

    var cursor uint64
    err = redisClient.ForEachMaster(ctx, func(ctx context.Context, nodeClient *redis.Client) error {
        for {
            keys, cursor := nodeClient.Scan(ctx, cursor, pattern, count).Val()
            if len(keys) > 0 {
                cmd := nodeClient.Del(ctx, keys...)
                if cmd.Err() != nil {
                    return cmd.Err()
                }
            }
            if cursor == 0 {
                break
            }
        }
        return nil
    })

    return err
}

Nesta função, a parte complicada é a contagem usada em cada comando de varredura do cliente do nó. Quando a defino como 1000000, tudo funciona bem. Mas quando uso um valor menor, como 100 ou mesmo 100000, este código trava em um loop infinito (o máximo que esperei foram 30 minutos). Ao usar 1000000 como contagem, geralmente leva segundos para excluir o padrão.

Mas estávamos bem usando 1 milhão até que nosso conjunto de dados do Redis ficou tão grande que o loop infinito aconteceu com essa contagem também. Atualmente, estou procurando uma maneira segura de excluir esses padrões sem me preocupar com essa contagem. E eu realmente quero saber o motivo pelo qual isso acontece.

Tentei defini-lo como -1, mas ainda trava. Também tentei usar o comando Unlink em vez do comando Del, mas o resultado é o mesmo.

go
  • 1 respostas
  • 91 Views
Martin Hope
vbulash
Asked: 2025-04-08 21:18:59 +0800 CST

Redigo: argumentos errados para XADD

  • 7

Gosto dos fluxos do Redis porque, com eles, o Redis se torna um banco de dados IoT. O principal comando do Redis para adicionar algo ao fluxo é XADD:

XADD log * name Some_name_to_write text Some_text_to_write

Funciona bem.

Então tento usar o Redigo para fazer a mesma operação:

type LogEntry struct {
    Name string `json:"name"`
    Text string `json:"text"`
}

func (l *LogEntry) Push() error {
    var args []string // XADD arguments

    log.Printf("Log Entry: %+v\n", l)
    args = make([]string, 6)
    args = append(args, "log") // Stream key
    args = append(args, "*")   // Auto-generated stream ID
    args = append(args, "name", l.Name)
    args = append(args, "text", l.Text)
    log.Printf("Args for XADD: %+v\n", args)

    new := make([]any, len(args))
    for index, value := range args {
        new[index] = value
    }

    _, err := connection.Do("XADD", new...)
    if err != nil {
        log.Println("XADD error", err)
        return err
    }

    return nil
}

connectionaqui está redis.Conn.

Este código produz a seguinte saída:

2025-04-08 16:03:08 2025/04/08 13:03:08 Log Entry: &{Name:Some_name_to_write Text:Some_text_to_write}
2025-04-08 16:03:08 2025/04/08 13:03:08 Args for XADD: [      log * name Some_name_to_write text Some_text_to_write]
2025-04-08 16:03:08 2025/04/08 13:03:08 XADD error ERR Invalid stream ID specified as stream command argument

Então, vejo que os argumentos são conn.Doexatamente os mesmos que usei antes na CLI.

O que há de errado aqui?

go
  • 1 respostas
  • 20 Views
Martin Hope
hankeyyh
Asked: 2025-04-05 15:40:18 +0800 CST

Verificar uma string de prefixo comparando-a com uma fatia de byte falha?

  • 3

Estou aprendendo o livro "Go Programing Language", quando ele introduz string, ele diz que Go usa sistema de codificação utf-8, então é fácil verificar se uma string é um prefixo/sufixo de outra string base. Use as funções abaixo:

func HasPrefix(s, prefix string) bool {
    return len(s) >= len(prefix) && s[:len(prefix)] == prefix
}
func HasSuffix(s, suffix string) bool {
    return len(s) >= len(suffix) && s[len(s)-len(suffix):] == suffix
}

Gostaria de saber se existe algum sistema de codificação que falharia ao usar as funções acima para verificar prefixo/sufixo?

go
  • 2 respostas
  • 51 Views
Martin Hope
RfDzDeveloper
Asked: 2025-04-02 17:46:44 +0800 CST

Fyne, como esticar abas com tabela para preencher a tela inteira do aplicativo?

  • 7

Tentei muitas maneiras diferentes de estender minha mesa para o restante do espaço livre do aplicativo.

A maneira mais simples de reproduzir meu problema é:

package main

import (
    "fmt"
    "strconv"
    "time"

    "fyne.io/fyne/v2"
    "fyne.io/fyne/v2/app"
    "fyne.io/fyne/v2/container"
    "fyne.io/fyne/v2/dialog"
    "fyne.io/fyne/v2/theme"
    "fyne.io/fyne/v2/widget"
)

type Reminders struct {
    ID        int64
    EventName string
    EventDay  time.Time
}

func getReminderSlice() [][]any {
    var slice [][]any

    reminders := []Reminders{{ID: 0, EventName: "First Event Name", EventDay: time.Now()},
        {ID: 1, EventName: "Second Name", EventDay: time.Now()}}

    slice = append(slice, []any{
        "ID",
        "Event Name",
        "Event Day",
        // "Start At",
        // "End At",
        // "Event Duration",
        // "Event Place",
        // "Priority",
        // "Description",
        "Delete?",
    })

    for _, r := range reminders {
        var currentRow []any

        currentRow = append(currentRow, strconv.FormatInt(r.ID, 10))
        currentRow = append(currentRow, r.EventName)
        currentRow = append(currentRow, r.EventDay.Format("2006-01-02"))
        // currentRow = append(currentRow, r.EventStartHour.Format("15:04"))
        // currentRow = append(currentRow, r.EventEndHour.Format("15:04"))
        // currentRow = append(currentRow, strconv.FormatFloat(r.EventDuration, 'f', -1, 64))
        // currentRow = append(currentRow, r.EventPlace)
        // currentRow = append(currentRow, strconv.Itoa(int(r.Priority)))
        // currentRow = append(currentRow, r.Description)
        // currentRow = append(currentRow, widget.NewButton("Delete", func() {}))

        slice = append(slice, currentRow)
    }
    return slice
}

func main() {
    data := getReminderSlice()

    myApp := app.New()
    myWindow := myApp.NewWindow("Table Widget")
    myWindow.Resize(fyne.NewSize(850, 530))

    // Create a table
    list := widget.NewTable(
        func() (int, int) {
            return len(data), len(data[0])
        },
        func() fyne.CanvasObject {
            container := container.NewVBox(widget.NewLabel(""))
            return container
        },
        func(i widget.TableCellID, o fyne.CanvasObject) {
            if i.Col == (len(data[0])-1) && i.Row != 0 {
                // last cell, put in a button
                w := widget.NewButtonWithIcon("Delete", theme.DeleteIcon(),
                    func() {
                        dialog.ShowConfirm("Delete?", "This will delete Event",
                            func(delete bool) {
                                if delete {
                                    fmt.Println("Deleted")

                                }
                                // refresh the reminders table
                                // refreshRemindersTable(db, uimanager)
                            }, myWindow)
                    })
                w.Importance = widget.HighImportance
                o.(*fyne.Container).Objects = []fyne.CanvasObject{
                    w,
                }
            } else {
                o.(*fyne.Container).Objects = []fyne.CanvasObject{
                    widget.NewLabel(data[i.Row][i.Col].(string)),
                }
            }
        })

    // trying to streach up table
    remindersContainer := container.NewBorder(
        nil,
        nil,
        nil,
        nil,
        container.NewAdaptiveGrid(1, list))
    colWidths := []float32{50, 150, 150, 150, 150, 150, 150, 150, 150}
    for i := range colWidths {
        list.SetColumnWidth(i, colWidths[i])
    }

    // tabs

    tabs := container.NewAppTabs(
        container.NewTabItemWithIcon("Reminders", theme.HomeIcon(), remindersContainer),
        // here will be the second tab
        // container.NewTabItemWithIcon("ToDo!", theme.ListIcon(), remindersContainer),
    )

    tabs.SetTabLocation(container.TabLocationLeading)

    // create toolbar

    toolbar := widget.NewToolbar(
        widget.NewToolbarSpacer(),
        widget.NewToolbarAction(theme.DocumentCreateIcon(), func() {
        }),
        widget.NewToolbarAction(theme.ViewRefreshIcon(), func() {}),
        widget.NewToolbarAction(theme.SettingsIcon(), func() {}),
    )

    // Creating finaly looking container
    finalContent := container.NewVBox(toolbar, tabs)
    myWindow.SetContent(finalContent)
    myWindow.ShowAndRun()
}


Depois de montar as partes do contêiner final para NewVBox(toolbar, tabs, table of a content) a tabela ficará pequena. Na posição horizontal não pode esticar bem. No caso de usar apenas tabs com tabela, tudo parece bom.

Eu tentei várias maneiras diferentes de consertar isso, mas não consigo descobrir o que está errado. Quero que o finalContent ocupe todo o espaço livre abaixo.

Espero ter expressado meus pensamentos de forma clara.

go
  • 1 respostas
  • 37 Views
Martin Hope
Ming
Asked: 2025-04-02 11:53:44 +0800 CST

servidor golang grpc e módulos grpc ui fx

  • 6

Estou tentando configurar módulos FX, mas tenho dúvidas e não consigo encontrar uma maneira de avançar. Basicamente, tenho um módulo para o servidor:

    func NewGRPCServer(
    lc fx.Lifecycle, log *zap.Logger, tracer trace.Tracer,
    srvsInterceptors []grpc.UnaryServerInterceptor, serverOpt []grpc.ServerOption,
) *grpc.Server {
    defaultRecoveryHandler := func(ctx context.Context, r interface{}) (err error) {
        logger.FromContext(ctx).Error("recovered from panic", zap.Any("panic", r), zap.Stack("stacktrace"))

        return status.Error(codes.Internal, "unexpected error")
    }

    interceptors := append([]grpc.UnaryServerInterceptor{
        LoggerToContextInterceptor(log),
        TracerToContextInterceptor(tracer),
        grpc_recovery.UnaryServerInterceptor(grpc_recovery.WithRecoveryHandlerContext(defaultRecoveryHandler)),
    }, srvsInterceptors...)

    otelHandler := otelgrpc.NewServerHandler(
        otelgrpc.WithTracerProvider(otel.GetTracerProvider()),
    )

    serverOpts := []grpc.ServerOption{
        grpc.ChainUnaryInterceptor(interceptors...),
        grpc.StatsHandler(otelHandler),
        grpc.KeepaliveEnforcementPolicy(
            keepalive.EnforcementPolicy{
                MinTime:             60 * time.Second,
                PermitWithoutStream: true,
            }),
        grpc.KeepaliveParams(
            keepalive.ServerParameters{
                Time:    60 * time.Second,
                Timeout: 10 * time.Second,
            },
        ),
    }

    serverOpts = append(serverOpts, serverOpt...)

    server := grpc.NewServer(serverOpts...)

    grpc_health_v1.RegisterHealthServer(server, health.NewServer())
    reflection.Register(server)

    return server
}

// NewListener creates a new network listener for the gRPC server using the gRPC server address parsed from the config.
func NewListener(cfg Config) (net.Listener, error) {
    lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.GRPC))
    if err != nil {
        return nil, fmt.Errorf("dial connection: %w", err)
    }

    return lis, nil
}

func GRPCModule() fx.Option {
    return fx.Module(
        "grpc",
        fx.Provide(
            fx.Annotate(
                NewGRPCServer,
                fx.ParamTags(``, ``, ``, `optional:"true"`, `optional:"true"`),
            ),
        ),
        fx.Invoke(func(lc fx.Lifecycle, server *grpc.Server, config Config, log *zap.Logger) {
            lc.Append(fx.Hook{
                OnStart: func(ctx context.Context) error {
                    lis, err := NewListener(config)
                    if err != nil {
                        return err
                    }

                    go func(srv *grpc.Server, logger *zap.Logger) {
                        logger.Info("Starting gRPC server")
                        if err := srv.Serve(lis); err != nil && err != grpc.ErrServerStopped {
                            logger.Error("gRPC server failed", zap.Error(err))
                        }
                    }(server, log)

                    return nil
                },
                OnStop: func(ctx context.Context) error {
                    server.GracefulStop()
                    return nil
                },
            })
        }),
    )
}

E um módulo para UI:

func NewGRPCUIServer(
    lc fx.Lifecycle,
    logger *zap.Logger,
    tracer trace.Tracer,
    config Config,
) (*http.Server, error) {
    logger.Info("enter on new grpc ui server.")

    rpcGrpcHost := fmt.Sprintf("0.0.0.0:%d", config.GRPC)
    keepAliveOpt := grpc.WithKeepaliveParams(keepalive.ClientParameters{
        Time:                60 * time.Second,
        Timeout:             10 * time.Second,
        PermitWithoutStream: true,
    })

    cc, err := grpc.NewClient(
        rpcGrpcHost,
        grpc.WithTransportCredentials(insecure.NewCredentials()),
        grpc.WithDefaultServiceConfig(`{"loadBalancingPolicy":"round_robin"}`),
        keepAliveOpt,
    )
    if err != nil {
        logger.Error("Failed to connect to gRPC server for UI", zap.Error(err))
        return nil, err
    }

    h, err := standalone.HandlerViaReflection(context.Background(), cc, rpcGrpcHost)
    if err != nil {
        logger.Error("Failed to create UI handler", zap.Error(err))
        return nil, err
    }

    mux := http.NewServeMux()
    mux.Handle("/grpc-ui/", http.StripPrefix("/grpc-ui", h))

    return httplib.NewHTTPServerFx(
        lc,
        httplib.Config{
            ServerAddr:         fmt.Sprintf(":%d", config.UI),
            ServerReadTimeout:  15 * time.Second,
            ServerWriteTimeout: 15 * time.Second,
        },
        logger,
        tracer,
        mux,
    )
}

type GRPCUIParams struct {
    fx.In

    WebServer *http.Server `name:"grpc-ui-server"`
    Logger    *zap.Logger
}

func GRPCUIModule() fx.Option {
    return fx.Module(
        "x:ui",
        fx.Provide(
            NewGRPCUIServer,
            fx.Annotate(
                NewGRPCUIServer,
                fx.ParamTags(``, ``, ``, ``, ``),
                fx.ResultTags(`name:"grpc-ui-server"`),
            ),
        ),
        fx.Invoke(func(params GRPCUIParams) {
            params.Logger.Info("gRPC UI Server initialized:", zap.String("address", params.WebServer.Addr))
        }),
    )
}

Mas por algum motivo está falhando em handlerViaReflection:

h, err := standalone.HandlerViaReflection(context.Background(), cc, rpcGrpcHost)
if err != nil {
    logger.Error("Failed to create UI handler", zap.Error(err))
    return nil, err
}

E está dando erro porque o servidor gRPC ainda não iniciou. Coloquei um breakpoint aqui no módulo do servidor:

fx.Invoke(func(lc fx.Lifecycle, server *grpc.Server, config Config, log *zap.Logger) {
    lc.Append(fx.Hook{
        OnStart: func(ctx context.Context) error {
            lis, err := NewListener(config)
            if err != nil {
                return err
            }

            go func(srv *grpc.Server, logger *zap.Logger) {
                logger.Info("Starting gRPC server")
                if err := srv.Serve(lis); err != nil && err != grpc.ErrServerStopped {
                    logger.Error("gRPC server failed", zap.Error(err))
                }
            }(server, log)

            return nil
        },

E não entra; ele sempre vai para o módulo UI primeiro. Ele cria o servidor: NewGRPCServer, mas nunca o inicializa. Alguém sabe como posso resolver isso?

go
  • 1 respostas
  • 28 Views
Martin Hope
Yossich
Asked: 2025-03-30 17:35:10 +0800 CST

Como fazer com que o Viper Unmarshal retorne um erro se uma variável de ambiente não estiver definida no Golang?

  • 6

Estou usando o Viper no Golang para carregar valores de configuração de variáveis ​​de ambiente. No entanto, quero que o viper.Unmarshal retorne um erro se uma variável de ambiente necessária não estiver definida.

Por padrão, se uma variável de ambiente estiver ausente, viper.Unmarshal não falha — ele simplesmente atribui o valor zero ao campo struct.

Aqui está meu código:

package main

import (
    "fmt"
    "log"

    "github.com/spf13/viper"
)

type Config struct {
    DatabaseURL string `mapstructure:"DATABASE_URL"`
}

func main() {
    viper.AutomaticEnv()

    var config Config
    if err := viper.Unmarshal(&config); err != nil {
        log.Fatalf("Error unmarshaling config: %v", err)
    }

    fmt.Println("Config:", config)
}

Se DATABASE_URL não estiver definido, config.DatabaseURL será apenas uma string vazia em vez de causar um erro.

Tentei usar viper.BindEnv("DATABASE_URL"), mas o Unmarshal ainda não falha quando DATABASE_URL está ausente.

No Viper, a função Unmarshal aceita hooks por meio de DecoderConfigOption. Olhando para o viper, descobri que a estrutura DecoderConfig tem um campo ErrorUnset:

// If ErrorUnset is true, then it is an error for there to exist  
// fields in the result that were not set in the decoding process  
// (extra fields). This only applies to decoding to a struct. This  
// will affect all nested structs as well.  
ErrorUnset bool 

No entanto, não tenho certeza de como passar essa configuração corretamente como um hook no Unmarshal. Se alguém souber como habilitar ErrorUnset usando DecoderConfigOption, obrigado!

Como posso fazer com que o viper.Unmarshal DecodeHook retorne um erro se uma variável de ambiente necessária não estiver definida?

go
  • 1 respostas
  • 46 Views
Martin Hope
Kingindanord
Asked: 2025-03-24 16:55:23 +0800 CST

Swaggo não analisa valores de exemplo de tags struct na documentação da API Go

  • 8

Estou usando o Swaggo para documentar meus endpoints da API Go. Tenho uma função de manipulador onde defini uma struct com tags de exemplo nos campos JSON struct, mas esses exemplos não estão aparecendo na IU do Swagger gerada.

// @Summary Register a new user
// @Description Creates a new user account. In development environment, the user is activated immediately. Otherwise, an activation email is sent.
// @Tags users
// @Accept json
// @Produce json
// @Param request body main.application.registerUserHandler.input true "User registration details"
// @Success 202 {object} object{user=data.User}
// @Router /users [post]
func (app *application) registerUserHandler(w http.ResponseWriter, r *http.Request) {
    var input struct {
        Name     string `json:"name" example:"John Doe"`
        Email    string `json:"email" example:"[email protected]"`
        Password string `json:"password" example:"SecurePass123!"`
    }
    // ... rest of the handler ...
}

A documentação do Swagger gera corretamente, mas os valores de exemplo das tags de exemplo na estrutura não estão aparecendo no esquema do corpo da solicitação.

insira a descrição da imagem aqui

Existe uma maneira de fazer o Swaggo reconhecer as tags de exemplo em estruturas aninhadas/em linha?

go
  • 1 respostas
  • 49 Views
Martin Hope
JPG
Asked: 2025-03-23 21:53:38 +0800 CST

não é possível receber mensagem pelo canal em Go [duplicado]

  • 4
Esta pergunta já tem respostas aqui :
Por que fmt.Println dentro de uma goroutine não imprime uma linha? (4 respostas)
Por que este programa não consegue imprimir nada usando goroutine? [duplicado] (2 respostas)
por que esse código não imprime nada com uma goroutine [duplicado] (2 respostas)
Nenhuma saída da goroutine (3 respostas)
O thread Golang não é executado todas as vezes [duplicado] (1 resposta)
Fechado ontem .

Eu estava aprendendo Go Channel. Fiz um pequeno programa abaixo emGo

package main
import "fmt"
func sample(mychan chan string) {
    fmt.Println("Go Go Go Go")
    fmt.Println("message received from channel is ", <-mychan)
}
func main() {
    messageChan := make(chan string)
    go sample(messageChan)
    messageChan <- "hello"
}

O que está acontecendo é que às vezes ele mostra a declaração "mensagem recebida...". E às vezes não mostra. E sempre mostra a declaração "Go Go Go...". Então por que ele pula a declaração "mensagem recebida". O que é esse comportamento? Estou confuso.

go
  • 1 respostas
  • 46 Views
Martin Hope
MasterShake20
Asked: 2025-03-22 22:06:58 +0800 CST

Precisa de ajuda para mostrar o eixo y no lado direito do gráfico para sobreposição de linhas com go-echarts

  • 6

Tenho um gráfico de barras simples que sobrepus com uma linha. As barras e as linhas são geradas a partir de dados diferentes, então o gráfico está distorcendo o tamanho das barras porque os dados da linha são significativamente maiores do que os dados das barras. Quero ter um eixo y separado para as linhas no lado direito do gráfico para evitar isso, mas não consigo encontrar nenhuma documentação para go-echarts sobre como fazer isso.

Aqui está uma imagem de como o gráfico está atualmente. Como você pode ver, as barras estão quase imperceptíveis.

insira a descrição da imagem aqui

Abaixo está meu código. A linha é adicionada na parte inferior do código. Alguém sabe como adicionar um eixo y no lado direito da linha?

// Sort the dates so that the x-axis is ordered.
    var dates []string
    for date := range data {
        dates = append(dates, date)
    }
    sort.Strings(dates)

    // Build series data for the bars (profit) and line (transaction count).
    var barData []opts.BarData
    for _, date := range dates {
        stat := data[date]
        barData = append(barData, opts.BarData{Value: stat.Profit})
    }

    // Create the bar chart for profit.
    bar := charts.NewBar()
    bar.SetGlobalOptions(
        charts.WithTitleOpts(opts.Title{
            Title:    "Daily Profit",
            Subtitle: "Profit in USDT",
        }),
        charts.WithLegendOpts(opts.Legend{
            Show: opts.Bool(false),
        }),
        charts.WithDataZoomOpts(opts.DataZoom{
            Type:  "slider",
            Start: 50,
            End:   100,
        }),
        // First y-axis (index 0) for Profit USDT; no explicit index needed.
        charts.WithYAxisOpts(
            opts.YAxis{
                Type: "value",
            },
        ),
    )
    bar.SetXAxis(dates).AddSeries("Profit USDT", barData)

    // Build series data for the bars (profit) and line (transaction count).
    var lineData []opts.LineData
    for _, date := range dates {
        stat := data[date]
        lineData = append(lineData, opts.LineData{Value: stat.Count, YAxisIndex: 1})
    }

    // Create the bar chart for profit.
    line := charts.NewLine()
    line.SetXAxis(dates).
        AddSeries("Transaction Count", lineData)
    line.SetGlobalOptions(
        // First y-axis (index 0) for Profit USDT; no explicit index needed.
        charts.WithYAxisOpts(
            opts.YAxis{
                Type: "value",
                Position: "right",
            },
        ),
    )
    line.ExtendYAxis(opts.YAxis{Type: "value", Position: "right", Show: opts.Bool(true)})
    
    bar.Overlap(line)

    return bar
go
  • 1 respostas
  • 29 Views
Martin Hope
Kendall Chenoweth
Asked: 2025-03-08 14:33:32 +0800 CST

Golang o que há de errado com este programa (Grupos de espera e canais)

  • 5

Eu tenho o seguinte código. É um exercício de aprendizado, então ele não faz nada obviamente útil. Se o valor wg.Add for 1, ele funciona. Se o valor wg.Add for 2, ele falha. Se eu remover a lógica do canal, ele funciona com um valor wg.Add de 2.

Alguma ideia do que estou fazendo errado?

package main

import (
    "fmt"
    "sync"
)

func popMessage(wg *sync.WaitGroup, m *sync.Mutex, i *int, c chan<- int) {
    m.Lock()
    *i++
    c <- *i
    m.Unlock()
    fmt.Printf("pop %d\n", *i)
    wg.Done()
}

func main() {
    var wg sync.WaitGroup
    var m sync.Mutex
    var intPtr *int

    c := make(chan int, 1)
    wg.Add(2)

    intPtr = new(int)
    *intPtr = 1
    go popMessage(&wg, &m, intPtr, c)
    go popMessage(&wg, &m, intPtr, c)
    go popMessage(&wg, &m, intPtr, c)
    wg.Wait()
    fmt.Printf("final %d\n", *intPtr)
    for x := range c {
        fmt.Printf("channel %d\n", x)
    }
}
go
  • 1 respostas
  • 54 Views

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve