'Programming'에 해당되는 글 1721건

  1. 2023.05.25 rust 소유권
  2. 2023.05.24 golang waitgroup
  3. 2023.05.24 golang echo server middleware
  4. 2023.05.24 golang 동시성
  5. 2023.05.20 rust was
  6. 2023.05.18 webGPU
  7. 2023.05.16 golang 고루틴과 채널
  8. 2023.05.16 golang switch, select
  9. 2023.05.16 golang uds
  10. 2023.05.16 golang mutex (sync)
Programming/rust2023. 5. 25. 12:46

rust에 추가된 개념으로 변수의 소유권 이라는 것이 있다.

좀 더 봐야 하지만, stack에 저장되는 경우에는 적용이 되지 않고 heap에 저장되는 변수들에 대해서 적용 될 것으로 예상된다.

변수 타입중 primitive와는 연관이 없을 것 같긴하다.

[링크 : https://doc.rust-lang.org/book/ch03-02-data-types.html]

 

소유자는 하나이다. 이게 포인트

Ownership Rules
First, let’s take a look at the ownership rules. Keep these rules in mind as we work through the examples that illustrate them:

Each value in Rust has an owner.
There can only be one owner at a time.
When the owner goes out of scope, the value will be dropped.

 

primitive 타입이라 그런건지 아니면 heap이 아닌 stack에 생성되는 변수이기 때문인진 좀 더 봐야 하지만

x = 5; y = x;의 경우에는 5의 소유권이 x에 있지만 y = x를 통해 x가 지닌 5의 소유권이 y에게로 가는 것으로 보이진 않는다.

Variables and Data Interacting with Move
Multiple variables can interact with the same data in different ways in Rust. Let’s look at an example using an integer in Listing 4-2.

    let x = 5;
    let y = x;
Listing 4-2: Assigning the integer value of variable x to y

We can probably guess what this is doing: “bind the value 5 to x; then make a copy of the value in x and bind it to y.” We now have two variables, x and y, and both equal 5. This is indeed what is happening, because integers are simple values with a known, fixed size, and these two 5 values are pushed onto the stack.

Now let’s look at the String version:

    let s1 = String::from("hello");
    let s2 = s1;
This looks very similar, so we might assume that the way it works would be the same: that is, the second line would make a copy of the value in s1 and bind it to s2. But this isn’t quite what happens.

 

간단(?)하게 생각하면 중괄호 끝날때가 scope의 끝이고

(사용자에게 보이진 않지만) 그때 마다 drop 함수가 호출되고 메모리 관리가 수행되는 것으로 생각된다.

그리고 이 때 소유권에 따라 사용되지 않는 변수는 사라지게 된다.

There is a natural point at which we can return the memory our String needs to the allocator: when s goes out of scope. When a variable goes out of scope, Rust calls a special function for us. This function is called drop, and it’s where the author of String can put the code to return the memory. Rust calls drop automatically at the closing curly bracket.

Note: In C++, this pattern of deallocating resources at the end of an item’s lifetime is sometimes called Resource Acquisition Is Initialization (RAII). The drop function in Rust will be familiar to you if you’ve used RAII patterns.

 

간단하게 생각하면... 메모리 포인터에 대해서 언어 레벨에서 관리하여

동일 포인터를 포인터 변수에 저장할 수 없도록 관리 하는 것이 소유권이라고 봐도 무방할 것 같다.

Earlier, we said that when a variable goes out of scope, Rust automatically calls the drop function and cleans up the heap memory for that variable. But Figure 4-2 shows both data pointers pointing to the same location. This is a problem: when s2 and s1 go out of scope, they will both try to free the same memory. This is known as a double free error and is one of the memory safety bugs we mentioned previously. Freeing memory twice can lead to memory corruption, which can potentially lead to security vulnerabilities.

To ensure memory safety, after the line let s2 = s1;, Rust considers s1 as no longer valid. Therefore, Rust doesn’t need to free anything when s1 goes out of scope. Check out what happens when you try to use s1 after s2 is created; it won’t work:

This code does not compile!
    let s1 = String::from("hello");
    let s2 = s1;

    println!("{}, world!", s1);
You’ll get an error like this because Rust prevents you from using the invalidated reference:

$ cargo run
   Compiling ownership v0.1.0 (file:///projects/ownership)
error[E0382]: borrow of moved value: `s1`
 --> src/main.rs:5:28
  |
2 |     let s1 = String::from("hello");
  |         -- move occurs because `s1` has type `String`, which does not implement the `Copy` trait
3 |     let s2 = s1;
  |              -- value moved here
4 |
5 |     println!("{}, world!", s1);
  |                            ^^ value borrowed here after move
  |
  = note: this error originates in the macro `$crate::format_args_nl` which comes from the expansion of the macro `println` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider cloning the value if the performance cost is acceptable
  |
3 |     let s2 = s1.clone();
  |                ++++++++

For more information about this error, try `rustc --explain E0382`.
error: could not compile `ownership` due to previous error
If you’ve heard the terms shallow copy and deep copy while working with other languages, the concept of copying the pointer, length, and capacity without copying the data probably sounds like making a shallow copy. But because Rust also invalidates the first variable, instead of being called a shallow copy, it’s known as a move. In this example, we would say that s1 was moved into s2. So, what actually happens is shown in Figure 4-4.

[링크 : https://doc.rust-lang.org/book/ch04-01-what-is-ownership.html]

 

+

단일 소유자면 어떻게 공유를 해? 했는데 검색해보니 다행히(!)

멀티 쓰레드 환경에서의 다중 소유권 내용이 존재한다.

다만 Rc는 thread safe하지 않으니 arc를 쓰란다.

Multiple Ownership with Multiple Threads
In Chapter 15, we gave a value multiple owners by using the smart pointer Rc<T> to create a reference counted value. Let’s do the same here and see what happens. We’ll wrap the Mutex<T> in Rc<T> in Listing 16-14 and clone the Rc<T> before moving ownership to the thread.
Filename: src/main.rs

This code does not compile!
use std::rc::Rc;
use std::sync::Mutex;
use std::thread;

fn main() {
    let counter = Rc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Rc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
Listing 16-14: Attempting to use Rc<T> to allow multiple threads to own the Mutex<T>

Once again, we compile and get... different errors! The compiler is teaching us a lot.

$ cargo run
   Compiling shared-state v0.1.0 (file:///projects/shared-state)
error[E0277]: `Rc<Mutex<i32>>` cannot be sent between threads safely
  --> src/main.rs:11:36
   |
11 |           let handle = thread::spawn(move || {
   |                        ------------- ^------
   |                        |             |
   |  ______________________|_____________within this `[closure@src/main.rs:11:36: 11:43]`
   | |                      |
   | |                      required by a bound introduced by this call
12 | |             let mut num = counter.lock().unwrap();
13 | |
14 | |             *num += 1;
15 | |         });
   | |_________^ `Rc<Mutex<i32>>` cannot be sent between threads safely
   |
   = help: within `[closure@src/main.rs:11:36: 11:43]`, the trait `Send` is not implemented for `Rc<Mutex<i32>>`
note: required because it's used within this closure
  --> src/main.rs:11:36
   |
11 |         let handle = thread::spawn(move || {
   |                                    ^^^^^^^
note: required by a bound in `spawn`
  --> /rustc/d5a82bbd26e1ad8b7401f6a718a9c57c96905483/library/std/src/thread/mod.rs:704:8
   |
   = note: required by this bound in `spawn`

For more information about this error, try `rustc --explain E0277`.
error: could not compile `shared-state` due to previous error

Wow, that error message is very wordy! Here’s the important part to focus on: `Rc<Mutex<i32>>` cannot be sent between threads safely. The compiler is also telling us the reason why: the trait `Send` is not implemented for `Rc<Mutex<i32>>` . We’ll talk about Send in the next section: it’s one of the traits that ensures the types we use with threads are meant for use in concurrent situations.

Unfortunately, Rc<T> is not safe to share across threads. When Rc<T> manages the reference count, it adds to the count for each call to clone and subtracts from the count when each clone is dropped. But it doesn’t use any concurrency primitives to make sure that changes to the count can’t be interrupted by another thread. This could lead to wrong counts—subtle bugs that could in turn lead to memory leaks or a value being dropped before we’re done with it. What we need is a type exactly like Rc<T> but one that makes changes to the reference count in a thread-safe way.

Atomic Reference Counting with Arc<T>
Fortunately, Arc<T> is a type like Rc<T> that is safe to use in concurrent situations. The a stands for atomic, meaning it’s an atomically reference counted type. Atomics are an additional kind of concurrency primitive that we won’t cover in detail here: see the standard library documentation for std::sync::atomic for more details. At this point, you just need to know that atomics work like primitive types but are safe to share across threads.

You might then wonder why all primitive types aren’t atomic and why standard library types aren’t implemented to use Arc<T> by default. The reason is that thread safety comes with a performance penalty that you only want to pay when you really need to. If you’re just performing operations on values within a single thread, your code can run faster if it doesn’t have to enforce the guarantees atomics provide.

Let’s return to our example: Arc<T> and Rc<T> have the same API, so we fix our program by changing the use line, the call to new, and the call to clone. The code in Listing 16-15 will finally compile and run:

Filename: src/main.rs

use std::sync::{Arc, Mutex};
use std::thread;

fn main() {
    let counter = Arc::new(Mutex::new(0));
    let mut handles = vec![];

    for _ in 0..10 {
        let counter = Arc::clone(&counter);
        let handle = thread::spawn(move || {
            let mut num = counter.lock().unwrap();

            *num += 1;
        });
        handles.push(handle);
    }

    for handle in handles {
        handle.join().unwrap();
    }

    println!("Result: {}", *counter.lock().unwrap());
}
Listing 16-15: Using an Arc<T> to wrap the Mutex<T> to be able to share ownership across multiple threads

This code will print the following:

Result: 10
We did it! We counted from 0 to 10, which may not seem very impressive, but it did teach us a lot about Mutex<T> and thread safety. You could also use this program’s structure to do more complicated operations than just incrementing a counter. Using this strategy, you can divide a calculation into independent parts, split those parts across threads, and then use a Mutex<T> to have each thread update the final result with its part.

Note that if you are doing simple numerical operations, there are types simpler than Mutex<T> types provided by the std::sync::atomic module of the standard library. These types provide safe, concurrent, atomic access to primitive types. We chose to use Mutex<T> with a primitive type for this example so we could concentrate on how Mutex<T> works.

[링크 : https://doc.rust-lang.org/book/ch16-03-shared-state.html]

 

스마트 포인터 하니 왜 cpp가 떠오르냐..(안봤음!)

아무튼 말 장난같은데

"소유권과 빌리는 컨셉에서 레퍼런스와 스마트 포인터 사이에는 추가적인 차이점이 있다." 라는 표현이 존재한다.

소유자가 1개가 원칙이나 스마트 포인터를 통해 소유자가 1 이상일 수 도 있다로 확장이 되려나?

Smart Pointers
A pointer is a general concept for a variable that contains an address in memory. This address refers to, or “points at,” some other data. The most common kind of pointer in Rust is a reference, which you learned about in Chapter 4. References are indicated by the & symbol and borrow the value they point to. They don’t have any special capabilities other than referring to data, and have no overhead.

Smart pointers, on the other hand, are data structures that act like a pointer but also have additional metadata and capabilities. The concept of smart pointers isn’t unique to Rust: smart pointers originated in C++ and exist in other languages as well. Rust has a variety of smart pointers defined in the standard library that provide functionality beyond that provided by references. To explore the general concept, we’ll look at a couple of different examples of smart pointers, including a reference counting smart pointer type. This pointer enables you to allow data to have multiple owners by keeping track of the number of owners and, when no owners remain, cleaning up the data.

Rust, with its concept of ownership and borrowing, has an additional difference between references and smart pointers: while references only borrow data, in many cases, smart pointers own the data they point to.

Though we didn’t call them as such at the time, we’ve already encountered a few smart pointers in this book, including String and Vec<T> in Chapter 8. Both these types count as smart pointers because they own some memory and allow you to manipulate it. They also have metadata and extra capabilities or guarantees. String, for example, stores its capacity as metadata and has the extra ability to ensure its data will always be valid UTF-8.

[링크 : https://doc.rust-lang.org/book/ch15-00-smart-pointers.html]

'Programming > rust' 카테고리의 다른 글

rust mut  (0) 2023.05.25
rust visibility and privacy  (0) 2023.05.25
rust was  (0) 2023.05.20
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
Posted by 구차니
Programming/golang2023. 5. 24. 16:10

고루틴이 종료되는 시점을 확인하는 방법으로 보면 되려나?

 

여러개의 고루틴을 종료할때 까지 기다리기 위해  wait gorup을 이용할 수 있다.

package main

import (
    "fmt"
    "sync"
    "time"
)

func worker(id int) {
    fmt.Printf("Worker %d starting\n", id)

    time.Sleep(time.Second)
    fmt.Printf("Worker %d done\n", id)
}

func main() {

    var wg sync.WaitGroup

    for i := 1; i <= 5; i++ {
        wg.Add(1)

        i := i

        go func() {
            defer wg.Done()
            worker(i)
        }()
    }

    wg.Wait()

}

[링크 : https://gobyexample.com/waitgroups]

[링크 : https://pyrasis.com/book/GoForTheReallyImpatient/Unit35/06]

[링크 : https://pkg.go.dev/sync#WaitGroup.Add]

'Programming > golang' 카테고리의 다른 글

golang echo 서버 이상한 버그 발견?  (0) 2023.06.27
go ws server client example  (0) 2023.06.08
golang echo server middleware  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
Posted by 구차니
Programming/golang2023. 5. 24. 15:41

golang의 echo를 이용해서 웹서버 만드는건 쉬운데

서버 돌려 두면 별도의 go routine으로 돌테니 어떻게 구성을 해야

IPC를 통해 받은 변수를 깨지지 않게 처리할 수 있을까?

 

걍 결론은.. mutex로 귀결인가?

func (s *Stats) Handle(c echo.Context) error {
s.mutex.RLock()
defer s.mutex.RUnlock()
return c.JSON(http.StatusOK, s)
}

func main() {
e := echo.New()

// Debug mode
e.Debug = true

//-------------------
// Custom middleware
//-------------------
// Stats
s := NewStats()
e.Use(s.Process)
e.GET("/stats", s.Handle) // Endpoint to get stats

// Server header
e.Use(ServerHeader)

// Handler
e.GET("/", func(c echo.Context) error {
return c.String(http.StatusOK, "Hello, World!")
})

// Start server
e.Logger.Fatal(e.Start(":1323"))
}

[링크 : https://echo.labstack.com/cookbook/middleware/]

'Programming > golang' 카테고리의 다른 글

go ws server client example  (0) 2023.06.08
golang waitgroup  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
Posted by 구차니
Programming/golang2023. 5. 24. 15:38

atomic 패키지는 특정 변수의 값 증가등에 대해서 atomic operation 해주는 것 같고 copy는 없는 것 같고

sync.mutex가 역시 가장 무난한 선택인가 싶다.

channel은 내가 원하는 패키지에서 사용가능한 방법은 아난 것 같군..

 

atomic > mutex > channel

[링크 : https://woojinger.tistory.com/100]

[링크 : https://dev-yakuza.posstree.com/ko/golang/goroutine/]

[링크 : https://pkg.go.dev/sync/atomic]

'Programming > golang' 카테고리의 다른 글

golang waitgroup  (0) 2023.05.24
golang echo server middleware  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
Posted by 구차니
Programming/rust2023. 5. 20. 13:48

'Programming > rust' 카테고리의 다른 글

rust visibility and privacy  (0) 2023.05.25
rust 소유권  (0) 2023.05.25
c에서 rust 호출하기  (0) 2023.05.11
rust 실행파일  (0) 2023.05.11
rust if문  (0) 2023.05.11
Posted by 구차니
Programming/web 관련2023. 5. 18. 14:14

유튜브에서 노마드 코더의 추천영상에 webGPU라는게 떠서 찾아보니

겁나 따끈한(고작 8일 지난..) 표준이다.

 

WebGPU
W3C Working Draft, 10 May 2023

[링크 : https://www.w3.org/TR/webgpu/]

[링크 : https://codelabs.developers.google.com/your-first-webgpu-app?hl=ko#0]

 

크롬94 베타 부터 webgpu 지원이 시작되었다는데(일단 글은 2021.09.11)

[링크 : https://www.clien.net/service/board/park/16489505]

 

webGL을 물리치고 대세가 될지 아니면 병행하게 될지 미래가 궁금해진다.

윈10 + 크롬 버전 113.0.5672.93(공식 빌드) (64비트)

 

ubuntu 18.04 + 버전 113.0.5672.126(공식 빌드) (64비트)

[링크 : https://webgpu.github.io/webgpu-samples/samples/shadowMapping]

 

+

리눅스에서는 webGPU가 disable인데.. 이걸 어떻게 켤 수 있으려나?

chrome://gpu/

 

[링크 : https://discourse.threejs.org/t/webgpu-example-not-working-in-ubuntu-20-04/40484]

Posted by 구차니
Programming/golang2023. 5. 16. 15:39

채널의 경우 1개로 해두면 하나가 들어갈 때 까지 해당 위치에서 블로킹 된다.

아래 예제는 받는 부분을 삭제했는데 그렇기에 채널을 통해 전송은 되지만 수신하지 않아 비워지지 않기 때문에

one을 출력하지 못하고 멈춰있는 것을 확인할 수 있다.

package main

import (
f "fmt"
"time"
)

func main() {

f.Println("select")

c1 := make(chan string)
c2 := make(chan string)

go func() {
time.Sleep(time.Second * 1)
f.Println("---")
c1 <- "one"
f.Println("one")
c1 <- "two"
f.Println("two")
c1 <- "three"
f.Println("three")
c1 <- "four"
f.Println("four")
}()

go func() {
time.Sleep(time.Second * 2)
c2 <- "fifth"
}()

for i := 0; i < 10000000000; i++ {
time.Sleep(time.Second)
}

}
$ go run go.go 
select
---
^Csignal: interrupt

 

다만, make를 통해 채널 버퍼를 n개로 만들어 두면, 넣을 수 있는 동안은 넣고 블로킹 되지 않고 넘어갈 수 있다.

package main

import (
f "fmt"
"time"
)

func main() {

f.Println("select")

c1 := make(chan string, 4)
c2 := make(chan string)

go func() {
time.Sleep(time.Second * 1)
f.Println("---")
c1 <- "one"
f.Println("one")
c1 <- "two"
f.Println("two")
c1 <- "three"
f.Println("three")
c1 <- "four"
f.Println("four")
}()

go func() {
time.Sleep(time.Second * 2)
c2 <- "fifth"
}()

for i := 0; i < 10000000000; i++ {
time.Sleep(time.Second)
}

}
$ go run go.go 
select
---
one
two
three
four
^Csignal: interrupt

 

[링크 : https://judo0179.tistory.com/88]

'Programming > golang' 카테고리의 다른 글

golang echo server middleware  (0) 2023.05.24
golang 동시성  (0) 2023.05.24
golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
golang mutex (sync)  (0) 2023.05.16
Posted by 구차니
Programming/golang2023. 5. 16. 11:32

golang switch는 신형 언어에 확장되서 그런가 꽤나 만능이다.

특이하게 조건식도 가능하고, 케이스 리스트도 된다.(c#에서 얼핏 봤던 느낌..)

package main

import (
"fmt"
"time"
)

func main() {
t := time.Now()
switch {
case t.Hour() < 12:
fmt.Println("Good morning!")
case t.Hour() < 17:
fmt.Println("Good afternoon.")
default:
fmt.Println("Good evening.")
}
}

[링크 :https://go.dev/tour/flowcontrol/11]

 

func WhiteSpace(c rune) bool {
switch c {
case ' ', '\t', '\n', '\f', '\r':
return true
}
return false
}

[링크 : https://hamait.tistory.com/1017]

 

아무튼 select는 channel 처리에 좀더 특화된 구문으로 생긴것 자체는 switch - case와 동일하게 작성된다.

다만, 동시에 여러개가 들어왔을 경우 랜덤하게 실행된다고 한다.

(생각이 꼬였는지 동시에 들어오면 가장 위에꺼 부터 실행되어야 하는거 아냐? 싶은데 동시성이니까 랜덤하게 처리되는건가..)

The select statement lets a goroutine wait on multiple communication operations.

A select blocks until one of its cases can run, then it executes that case. It chooses one at random if multiple are ready.

 

package main

import "fmt"

func fibonacci(c, quit chan int) {
x, y := 0, 1
for {
select {
case c <- x:
x, y = y, x+y
case <-quit:
fmt.Println("quit")
return
}
}
}

func main() {
c := make(chan int)
quit := make(chan int)
go func() {
for i := 0; i < 10; i++ {
fmt.Println(<-c)
}
quit <- 0
}()
fibonacci(c, quit)
}

[링크 : https://go.dev/tour/concurrency/5]

 

[링크 : https://edu.goorm.io/learn/lecture/2010/한-눈에-끝내는-고랭-기초/lesson/382961/채널-select문]

 

'Programming > golang' 카테고리의 다른 글

golang 동시성  (0) 2023.05.24
golang 고루틴과 채널  (0) 2023.05.16
golang uds  (0) 2023.05.16
golang mutex (sync)  (0) 2023.05.16
go 포맷터  (0) 2023.05.11
Posted by 구차니
Programming/golang2023. 5. 16. 10:46

쓸만하려나?

server client
package main

import (
"fmt"
"log"
"os"
"path/filepath"
"time"

"github.com/google/uuid"
"github.com/johnsiilver/golib/ipc/uds"
)

func main() {
socketAddr := filepath.Join(os.TempDir(), uuid.New().String())

cred, _, err := uds.Current()
if err != nil {
panic(err)
}

// This will set the socket file to have a uid and gid of whatever the
// current user is. 0770 will be set for the file permissions (though on some
// systems the sticky bit gets set, resulting in 1770.
serv, err := uds.NewServer(socketAddr, cred.UID.Int(), cred.GID.Int(), 0770)
if err != nil {
panic(err)
}

fmt.Println("Listening on socket: ", socketAddr)

// This listens for a client connecting and returns the connection object.
for conn := range serv.Conn() {
conn := conn

// We spinoff handling of this connection to its own goroutine and
// go back to listening for another connection.
go func() {
// We are checking the client's user ID to make sure its the same
// user ID or we reject it. Cred objects give you the user's
// uid/gid/pid for filtering.
if conn.Cred.UID.Int() != cred.UID.Int() {
log.Printf("unauthorized user uid %d attempted a connection", conn.Cred.UID.Int())
conn.Close()
return
}
// Write to the stream every 10 seconds until the connection closes.
for {
if _, err := conn.Write([]byte(fmt.Sprintf("%s\n", time.Now().UTC()))); err != nil {
conn.Close()
}
time.Sleep(10 * time.Second)
}
}()
}
}
package main

import (
"flag"
"fmt"
"io"
"os"

"github.com/johnsiilver/golib/ipc/uds"
)

var (
addr = flag.String("addr", "", "The path to the unix socket to dial")
)

func main() {
flag.Parse()

if *addr == "" {
fmt.Println("did not pass --addr")
os.Exit(1)
}

cred, _, err := uds.Current()
if err != nil {
panic(err)
}

// Connects to the server at socketAddr that must have the file uid/gid of
// our current user and one of the os.FileMode specified.
client, err := uds.NewClient(*addr, cred.UID.Int(), cred.GID.Int(), []os.FileMode{0770, 1770})
if err != nil {
fmt.Println(err)
os.Exit(1)
}

// client implements io.ReadWriteCloser and this will print to the screen
// whatever the server sends until the connection is closed.
io.Copy(os.Stdout, client)
}

[링크 : https://github.com/johnsiilver/golib/blob/v1.1.2/ipc/uds/example/server/server.go]

[링크 : https://github.com/johnsiilver/golib/blob/v1.1.2/ipc/uds/example/client/client.go]

[링크 : https://pkg.go.dev/github.com/johnsiilver/golib/ipc/uds]

'Programming > golang' 카테고리의 다른 글

golang 고루틴과 채널  (0) 2023.05.16
golang switch, select  (0) 2023.05.16
golang mutex (sync)  (0) 2023.05.16
go 포맷터  (0) 2023.05.11
golang echo directory listing  (0) 2023.05.08
Posted by 구차니
Programming/golang2023. 5. 16. 10:36

 

package main

import (
"fmt"
"sync"
"time"
)

// SafeCounter is safe to use concurrently.
type SafeCounter struct {
mu sync.Mutex
v  map[string]int
}

// Inc increments the counter for the given key.
func (c *SafeCounter) Inc(key string) {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
c.v[key]++
c.mu.Unlock()
}

// Value returns the current value of the counter for the given key.
func (c *SafeCounter) Value(key string) int {
c.mu.Lock()
// Lock so only one goroutine at a time can access the map c.v.
defer c.mu.Unlock()
return c.v[key]
}

func main() {
c := SafeCounter{v: make(map[string]int)}
for i := 0; i < 1000; i++ {
go c.Inc("somekey")
}

time.Sleep(time.Second)
fmt.Println(c.Value("somekey"))
}

[링크 : https://go.dev/tour/concurrency/9]

 

func (*Mutex) Lock ¶
func (m *Mutex) Lock()
Lock locks m. If the lock is already in use, the calling goroutine blocks until the mutex is available.

func (*Mutex) TryLock ¶
added in go1.18
func (m *Mutex) TryLock() bool
TryLock tries to lock m and reports whether it succeeded.

Note that while correct uses of TryLock do exist, they are rare, and use of TryLock is often a sign of a deeper problem in a particular use of mutexes.

func (*Mutex) Unlock ¶
func (m *Mutex) Unlock()
Unlock unlocks m. It is a run-time error if m is not locked on entry to Unlock.

A locked Mutex is not associated with a particular goroutine. It is allowed for one goroutine to lock a Mutex and then arrange for another goroutine to unlock it.

[링크 : https://pkg.go.dev/sync#Mutex.Lock]

 

[링크 : https://mingrammer.com/gobyexample/mutexes/]

[링크 : https://www.joinc.co.kr/w/GoLang/example/mutexex]

[링크 : https://pyrasis.com/book/GoForTheReallyImpatient/Unit35]

 

'Programming > golang' 카테고리의 다른 글

golang switch, select  (0) 2023.05.16
golang uds  (0) 2023.05.16
go 포맷터  (0) 2023.05.11
golang echo directory listing  (0) 2023.05.08
golang websocket binary  (0) 2023.03.28
Posted by 구차니