- 于 2014-11-04 加入CSDN
-
获得0次点赞
-
内容获得0次评论
-
获得1次收藏
- 最近
- 文章
- 资源
- 问答
- 课程
- 帖子
- 收藏
- 关注/订阅




我靠运气解决的Golang僵局,需要说明
I'm trying to understand go channel and go routine. To do so, I'm doing online exercises. I found one here: http://whipperstacker.com/2015/10/05/3-trivial-concurrency-exercises-for-the-confused-newbie-gopher/
I resolved the 3rd one (named "Internet cafe"). But there's something I resolved by "luck", and it's bother me because I don't understand my issue and why my "hack" fixed it.
In my code below, I replace "enterChan <- next" by "go func() { enterChan <- next }()", and it solved my deadlock.
Can someone explain to me why it deadlock before, and why it works with this hack ? Is it a proper solution, or an ugly one ?
Don't hesitate to criticize my code, I'm searching to improve :)
Many thanks!
This is my code:
package main
import (
"fmt"
"math/rand"
"strconv"
"time"
)
const (
maxNumberOfUser = 8
)
func useComputer(tourist string, leaverChan chan string) {
seed := rand.NewSource(time.Now().UnixNano())
random := rand.New(seed)
fmt.Println(tourist, "is online")
d := random.Intn(120-15) + 15
time.Sleep(time.Duration(d) * time.Millisecond * 10)
fmt.Println(tourist, "is done, having spent", d, "minutes online.")
leaverChan <- tourist
}
func manageUsers(enterChan, leaverChan chan string, stopChan chan struct{}) {
nbUsed := 0
queue := make([]string, 0)
for {
select {
case tourist := <-enterChan:
if nbUsed < maxNumberOfUser {
nbUsed++
go useComputer(tourist, leaverChan)
} else {
fmt.Println(tourist, "waiting for turn.")
queue = append(queue, tourist)
}
case tourist := <-leaverChan:
nbUsed--
fmt.Println(tourist, "is leaving, number of free place is now:", maxNumberOfUser-nbUsed)
if len(queue) > 0 {
next := queue[0]
queue = queue[1:]
go func() {
enterChan <- next
}()
} else if nbUsed == 0 {
close(stopChan)
return
}
}
}
}
func main() {
enterChan := make(chan string)
leaverChan := make(chan string)
stopChan := make(chan struct{})
go manageUsers(enterChan, leaverChan, stopChan)
for i := 1; i <= 25; i++ {
enterChan <- "Tourist " + strconv.Itoa(i)
}
<-stopChan
fmt.Println("The place is empty, let's close up and go to the beach!")
}

处理SIGSEGV与恢复?
The signal package states:
Synchronous signals are signals triggered by errors in program execution: SIGBUS, SIGFPE, and SIGSEGV. These are only considered synchronous when caused by program execution, not when sent using os.Process.Kill or the kill program or some similar mechanism. In general, except as discussed below, Go programs will convert a synchronous signal into a run-time panic.
However, it seems recover()
is not catching this.
Program:
package main
import (
"fmt"
"unsafe"
"log"
)
func seeAnotherDay() {
defer func() {
if p := recover(); p != nil {
err := fmt.Errorf("recover panic: panic call")
log.Println(err)
return
}
}()
panic("oops")
}
func notSoMuch() {
defer func() {
if p := recover(); p != nil {
err := fmt.Errorf("recover panic: sigseg")
log.Println(err)
return
}
}()
b := make([]byte, 1)
log.Println("access some memory")
foo := (*int)(unsafe.Pointer(uintptr(unsafe.Pointer(&b[0])) + uintptr(9999999999999999)))
fmt.Print(*foo + 1)
}
func main() {
seeAnotherDay()
notSoMuch()
}
Output:
2017/04/04 12:13:16 recover panic: panic call
2017/04/04 12:13:16 access some memory
unexpected fault address 0xb01dfacedebac1e
fatal error: fault
[signal SIGSEGV: segmentation violation code=0x1 addr=0xb01dfacedebac1e pc=0x108aa8a]
goroutine 1 [running]:
runtime.throw(0x10b5807, 0x5)
/usr/local/go/src/runtime/panic.go:596 +0x95 fp=0xc420043ea8 sp=0xc420043e88
runtime.sigpanic()
/usr/local/go/src/runtime/signal_unix.go:297 +0x28c fp=0xc420043ef8 sp=0xc420043ea8
main.notSoMuch()
/Users/kbrandt/src/sigseg/main.go:32 +0xca fp=0xc420043f78 sp=0xc420043ef8
main.main()
/Users/kbrandt/src/sigseg/main.go:37 +0x25 fp=0xc420043f88 sp=0xc420043f78
runtime.main()
/usr/local/go/src/runtime/proc.go:185 +0x20a fp=0xc420043fe0 sp=0xc420043f88
runtime.goexit()
/usr/local/go/src/runtime/asm_amd64.s:2197 +0x1 fp=0xc420043fe8 sp=0xc420043fe0
exit status 2
Is there any way I could handle SIGSEGV in a way localized to certain parts of the code?


不能在Magento2中使用带有自定义表的getCollection
I'm trying to follow Alan Storm's tutorial here. The code works fine when I try to insert or retrieve a single record, but it cracks when I use collections. I followed all steps he illustrated in the tutorial, which drives me crazy because only collections wouldn't work!!
public function __construct(
\Magento\Backend\App\Action\Context $context,
\Vendor\Mymodule\Model\ConfigurationsFactory $myClass
) {
$this->myClass = $myClass;
parent::__construct($context);
}
public function execute() {
$todo = $this->myClass->create();
$collection = $todo->getCollection();
foreach($collection as $item)
{
var_dump('Item ID: ' . $item->getConfigId());
var_dump($item->getData());
}
exit;
}
This gives the following error:
Vendor\Mymodule\Model\Configurations does not extend \Magento\Framework\DataObject
The code for configurations model is as below
namespace Vendor\Mymodule\Model;
use Magento\Framework\Model\AbstractModel;
class Configurations extends AbstractModel
{
protected function _construct()
{
$this->_init('Vendor\Mymodule\Model\ResourceModel\Configurations');
}
}
ResourceModel
namespace Vendor\Mymodule\Model\ResourceModel;
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
class Configurations extends AbstractDb
{
protected function _construct()
{
$this->_init('vendor_configurations','config_id');
}
}
Collection
namespace Vendor\Mymodule\Model\ResourceModel\Configurations;
class Collection extends \Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection
{
protected function _construct()
{
$this->_init('
Vendor\Mymodule\Model\Configurations',
'Vendor\Mymodule\Model\ResourceModel\Configurations');
}
}
any hints would be really appreciated. Thanks

AJAX页面 - 如何使用#home等
I'm trying to make AJAX pages using the post from Tutorialzine.
This script makes pages appear using AJAX. The problem is that the script works with numbers, example: http://example.com/#page1
, http://example.com/#page2
etc..
How to make this script so it doesn't need the #page1
or #page2
in the URL, but #home
etc..
Sorry if I explained this wrong, English isn't my native language and it's hard for me to explain.
index.html
<script type="text/javascript" src="script.js"></script>
<ul id="navigation">
<li><a href="#page1">Page 1</a></li>
<li><a href="#page2">Page 2</a></li>
<li><a href="#page3">Page 3</a></li>
<li><a href="#page4">Page 4</a></li>
<li><img id="loading" src="img/ajax_load.gif" alt="loading" /></li>
</ul>
<div id="pageContent"></div>
script.js
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
load_page.php
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else echo 'There is no such page!';
?>


查询字符串中带#的值不会收到完整数据
I have one url with one code. http://www.example.com/exam.php?id=rteter#443545
Now when I click this URL, the value of the id is rteter, means it returns me only portion of code before #.
I have not sent the link with urlencode so please do not give that solutions. Links are already sent, is they any way by which I can get the full value in my php code?
Martha
