1

I have a code like,

Routine 1 {
runtime.LockOSThread()
print something
send int to routine 2
runtime.UnlockOSThread

}

Routine 2 {
runtime.LockOSThread()
print something
send int to routine 1
runtime.UnlockOSThread

}


main {
go Routine1
go Routine2
}

I use run time lock-unlock because, I don't want that printing of Routine 1 will mix with Routine 2. However, after execution of above code, it outputs same as without lock-unlock (means printing outputs mixed). Can anybody help me why this thing happening and how to force this for happening.

NB: I give an example of print something, however there are lots of printing and sending events.

Arpssss
  • 3,850
  • 6
  • 36
  • 80

3 Answers3

3

If you want to serialize "print something", e.g. each "print something" should perform atomically, then just serialize it.

You can surround "print something" by a mutex. That'll work unless the code deadlock because of that - and surely it easily can in a non trivial program.

The easy way in Go to serialize something is to do it with a channel. Collect in a (go)routine everything which should be printed together. When collection of the print unit is done, send it through a channel to some printing "agent" as a "print job" unit. That agent will simply receive its "tasks" and atomically print each one. One gets that atomicity for free and as an important bonus the code can not deadlock easily no more in the simple case, where there are only non interdependent "print unit" generating goroutines.

I mean something like:

func printer(tasks chan string) {
        for s := range tasks {
                fmt.Printf(s)
        }
}

func someAgentX(tasks chan string) {
        var printUnit string
        //...
        tasks <- printUnit
        //...
}

func main() {
        //...
        tasks := make(chan string, size)
        go printer(tasks)
        go someAgent1(tasks)
        //...
        go someAgentN(tasks)
        //...
        <- allDone
        close(tasks)
}
zzzz
  • 87,403
  • 16
  • 175
  • 139
  • I have used this. However, there are not only print something in-between lock and unlock, there are some sending event also, like send int to routine 1. I have to cover those also. Can you suggest anything about that ? – Arpssss Dec 04 '11 at 21:59
  • @Arpssss: No, I can't suggest anything specific about that. It's next to impossible without understanding the (whole) problem you're solving. But probably no one is going to dive into hundreds of lines of code. If the problem can't be explained in a small amount of code or by any other clear and concise way then I'm afraid you're out of luck on SO or anywhere else. – zzzz Dec 04 '11 at 22:07
  • I tried to use sync-mutex also http://play.golang.org/p/CbdrRHvbnQ. However, in that code, I could not get why routines are executing one after another, not executing concurrently. Can you suggest anything about that or any mistakes in logic of sync-mutex ? – Arpssss Dec 04 '11 at 22:18
  • Go playground is by design limited. It runs only single threaded. It's also frozen in time, has no file access except stdio/stderr and perhaps more. You have to exercise your code locally to get access to the full/standard run time environment. And by the way, the linked code with those three mutexes locked in every goroutine, though in different order, surprises me a lot by not immediately deadlocking as I don't understand its meaning at all. I guess it'll deadlock "by design" with GOMAXPROCS > 1 outside the playground. – zzzz Dec 04 '11 at 22:30
  • You are correct. In my desktop application, it showing deadlock. Actually, I am trying to implement sync-mutex mechanism. Where, while routine 1 is executing fmt.Println("value of z"), every other thread is blocked. Any correction on that implementation ? – Arpssss Dec 04 '11 at 22:34
  • @Arpssss: Yes. Throw away all mutexes and use channels to write a clean, understandable (to yourself too) code. – zzzz Dec 04 '11 at 22:42
  • Here you can find a simple clean code, http://play.golang.org/p/jJDY8LFkKu. Here I want to put two prints and sending event inside mutex (for routine 1) thus routine 2 can't interrupt it. Can you help me how is it possible. – Arpssss Dec 04 '11 at 22:58
1

What runtime.LockOSThread does is prevent any other goroutine from running on the same thread. It forces the runtime to create a new thread and run Routine2 there. They are still running concurrently but on different threads.

You need to use sync.Mutex or some channel magic instead.

You rarely need to use runtime.LockOSThread but it can be useful for forcing some higher priority goroutine to run on a thread of it's own.

package main

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

var m sync.Mutex

func printing(s string) {
    m.Lock() // Other goroutines will stop here if until m is unlocked
    fmt.Println(s)
    m.Unlock() // Now another goroutine at "m.Lock()" can continue running
}

func main() {
    for i := 0; i < 10; i++ {
        go printing(fmt.Sprintf("Goroutine #%d", i))
    }

    <-time.After(3e9)
}
RCE
  • 1,681
  • 13
  • 12
  • I have changed my question to make it more clearer. About lock unlock, you are quite correct. However, can tou give a simple example code, how can I use sync-mutex in the example above. – Arpssss Dec 04 '11 at 22:06
  • I tried to use sync-mutex also http://play.golang.org/p/CbdrRHvbnQ. However, in that code, I could not get why routines are executing one after another, not executing concurrently. Can you suggest anything about that or any mistakes in logic of sync-mutex ? – Arpssss Dec 04 '11 at 22:18
  • or any correction of that.Actually, I am trying to implement sync-mutex mechanism. Where, while routine 1 is executing fmt.Println("value of z"), every other thread is blocked. Any correction on that implementation ? – Arpssss Dec 04 '11 at 22:38
  • I added a simple example. I hope it makes it more clear. Once a mutex is locked, other goroutines can't pass it until it's unlocked. – RCE Dec 04 '11 at 23:09
  • Thanks. However, it creates deadlock in this http://play.golang.org/p/Ojx6aOIAUR. Can you help me how to solve this ? – Arpssss Dec 04 '11 at 23:18
  • thanks. It is nice example. Actually, I have scenario like http://play.golang.org/p/-uoQSqBJKS. Where, it is expected after finishing sending func send must unlock. However, it is not doing so.Can you help me how to solve this ? – Arpssss Dec 04 '11 at 23:23
0

I think, this is because of runtime.LockOSThread(),runtime.UnlockOSThread does not work all time. It totaly depends on CPU, execution environment etc. It can't be forced by anyother way.

alessandro
  • 1,681
  • 10
  • 33
  • 54