I tried ,  it is *not* in the same thread.   if cwork and gowork call
thread-unsafe api,  it will crash

package main

// #include <pthread.h>
import "C"
import (
   _ "fmt"
   "time"
   "runtime"
)

var go_done = make(chan bool, 1)
var c_done = make(chan bool, 1)

func init() {
   runtime.GOMAXPROCS(1)
   //runtime.LockOSThread()
}

func GoWork() {
   //runtime.LockOSThread()
   println("GoWork thread=", C.pthread_self())
   go_done <- true
   for {
      <-c_done
      println("c done, now go thread=",C.pthread_self())
      time.Sleep(time.Second)
      go_done <- true
   }

}

func main() {}

//export Start
func Start() {
   //runtime.LockOSThread()
   println("C Start thread=", C.pthread_self())
   go GoWork()
   //for {
   // <-go_done
   // println("go done, now c wokr")
   // time.Sleep(time.Second)
   // c_done <- true
   //}
}

//export CWork
func CWork() {
   <-go_done
   println("go done, now c thread=",C.pthread_self())
   time.Sleep(time.Second)
   c_done <- true
}

#include <stdio.h>
#include <pthread.h>
#include "sync.h"



int main (){
    printf("main thread=%p\n", pthread_self());
    Start();
    while(1) {
        CWork();

    }

    return 0;
}



2017-04-28 16:17 GMT+08:00 <djad...@gmail.com>:

>
>
> On Friday, April 28, 2017 at 9:18:03 AM UTC+3, hui zhang wrote:
>>
>> How let go and c code work Alternately in the same thread with
>> goroutine(corouting mechanism)
>> Check the code below.  c and go code in one thread they just do work 1 by
>> 1.
>> Expected Result
>>
>>> Do CWork
>>> Do GoWork
>>> Do CWork
>>> Do GoWork
>>> Do CWork
>>> .....
>>
>>
>> //c code
>>> void CWork() {
>>> while(1) {
>>>    --Print Do CWork
>>>    --Coroutine Stop
>>>     --switch to GoWork()
>>> }
>>> }
>>> int main() {
>>> CWork();
>>> }
>>> //go code
>>> func GoWork() {
>>> for {
>>>     --Print Do GoWork
>>>    --Coroutine Stop
>>>     --switch back to CWork()
>>> }
>>> }
>>
>>
>>
>>
>
>
> Hi, simplest solution:
>
> //c code
>> void CWork() {
>>         --Print Do CWork
>> }
>> int main() {
>>         for {
>>         C.CWork()
>> GoWork()
>>         }
>> }
>>
>> //go code
>> func GoWork() {
>>         --Print Do GoWork
>> }
>
>
>
>  Djadala
>
> --
> You received this message because you are subscribed to a topic in the
> Google Groups "golang-nuts" group.
> To unsubscribe from this topic, visit https://groups.google.com/d/
> topic/golang-nuts/Yaay2_UaIxU/unsubscribe.
> To unsubscribe from this group and all its topics, send an email to
> golang-nuts+unsubscr...@googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to