请教golang的channel的使用技巧,帮看看这段代码如何优化 20C
 /**
 * 通过channel实现并发信息的累计
 * 这里单独开一个endTaskNumChan是考虑到可能会有多种信息的累计,比如成功信息,失败信息
 */
package main

import (
    "fmt"
    "time"
)

var (
    msgs           string      //信息
    msgChan        chan string //单条信息通道
    endTaskNumChan chan bool   //完成任务通知
    endTaskNum     int         //已完成任务数
)

func main() {
    //因为考虑到其他地方如果循环调用,这里需要重置一下
    msgs = ""
    msgChan = make(chan string)
    endTaskNumChan = make(chan bool)
    endTaskNum = 0
    for i := 0; i < 5; i++ {
        go addMsg(i)
    }
L:
    for {
        select {
        case msg, ok := <-msgChan: //获取单条信息
            if ok {
                msgs = fmt.Sprint(msgs, msg)
            }
        case <-endTaskNumChan: //获取处理完通知
            endTaskNum++
            if endTaskNum == 5 { //如果已完成任务等于总任务(退出这里是否有更好的办法??)
                close(msgChan)
                break L
            }
        }
    }
    fmt.Println("msgs", msgs)
}
func addMsg(i int) {
    defer func() {
        endTaskNumChan <- true
    }()
    time.Sleep(1 * time.Second)
    msgChan <- fmt.Sprint("当前是:", i, "\n")
}

0

2个回答

直接用WaitGroup等待各个子任务都完成。进行结束处理

0

源程序输出:

msgs 当前是:2
当前是:1
当前是:4
当前是:0
当前是:3

代码:使用工作池做缓冲,锁保证msg存入到msgs中。

package main

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

var (
    msgs       string     //信息
    msgChan    chan bool  //单条信息通道
    endTaskNum int        //已完成任务数
    mt         sync.Mutex //锁
)

func main() {
    msgs = ""
    endTaskNum = 5
    msgChan = make(chan bool, 1)

    var wg sync.WaitGroup
    for i := 0; i < endTaskNum; i++ {
        wg.Add(1)
        go addMsg(i, &wg)

    }
    wg.Wait()

    fmt.Println("msgs", msgs)
}
func addMsg(i int, wg *sync.WaitGroup) {
    defer func() {
        wg.Done()
    }()
    time.Sleep(1 * time.Second)
    msg := fmt.Sprint("当前是:", i, "\n")
    mt.Lock()
    msgs = fmt.Sprint(msgs, msg)
    mt.Unlock()
}

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
golang channel的使用技巧
go的横空出世,让很多人眼前一亮,它的语法以简洁著称,并且它对多核并发的原生支持,让他在云计算和分布式领域展露头脚,它的核心围绕channel和goroutine展开。下面我们来介绍一下channel的基本用法。 1 信号量的传递
帮看看这段代码
rnrnfunction doPlay(strUrl)rnrn try rn if (TPTrigger.Execute(0, strUrl)) rn bInstalled = true;rn rn else rn bInstalled =false;rn rn catch (e) rn bInstalled = false;rn rn rn if (! bInstalled) rn doNotFound();rn rnrn//-->rnrnrnrn 合同法学(李旦伟)(2002秋A) 多 媒 体 教 学 课 件 清 单 rn rn 视 频 片 段 名rn 网通宽带 rn 用户点播rn 电信宽带 rn 用户点播rn 校园网 rn 用户点播rn rn 合同法学01 合同法学02 合同法学03 合同法学04 合同法学05 合同法学06 合同法学07 合同法学08 合同法学09
帮看看这段代码!
private void checkedListBox1_ItemCheck(object sender, System.Windows.Forms.ItemCheckEventArgs e)rn rn rn if(checkedListBox1.GetItemChecked(checkedListBox1.SelectedIndex) == true listBox1.Items.Add(checkedListBox1.SelectedItem.ToString());rn rn else rnlistBox1.Items.Remove(checkedListBox1.SelectedItem.ToString());rn rnrn//程序的功能是当CheckedListBox上的列表项被勾选的话rnrnrn就向ListBox1里添加所选CheckedListBox列表的内容,以上的代码无法实现,但把rnrnlistBox1.Items.Add(checkedListBox1.SelectedItem.ToString()); 和rnrnlistBox1.Items.Remove(checkedListBox1.SelectedItem.ToString());rn换个位置就好了,rnrn我实在不明白checkedListBox1.GetItemChecked这个方法的作用是当相应项被勾选的话返回True,那为什么要换了才行,rn当勾选的时候ADD,否则就Remove,这错了吗?盼答,谢谢rn
请教如何优化这段代码
我找到1段代码,是有关端口检测的:rnprivate void button1_Click(object sender, EventArgs e)rnrn//扫描端口 rn int iStart=(int)this.numericUpDown1.Value; rn int iEnd=(int)this.numericUpDown2.Value; rn try rn rn this.progressBar1.Minimum=iStart; rn this.progressBar1.Maximum=iEnd; rn this.richTextBox1.Text="程序开始扫描端口:\n"; rn this.richTextBox1.Update(); rn for(int i=iStart ;i
请教!看看这段代码怎么优化些
Cchanzhuang* pCZ;//class Cchanzhuang : public CRecordsetrnCDatabase m_database;rnrnm_database.Open("mapgisDSN");rnpCZ =new Cchanzhuang(&m_database);rnrnint len=0;rnfloat* qingjiao;rntryrn if(pCZ->IsOpen())rn pCZ->Close();rnrn pCZ->Open(CRecordset::snapshot);rn while(!pCZ->IsEOF())rn len++;rn pCZ->MoveNext();rn rn qingjiao=new float[len];rn pCZ->MoveFirst();rn while(!pCZ->IsEOF())rn qingjiao[len++]=pCZ->m_qingjiao;rn pCZ->MoveNext();rn rn if(pCZ->IsOpen())rn pCZ->Close();rncatch(CDBException *e)rn e->ReportError();rnrndelete[] qingjiao;rnrn这代码读取数据库表的数目赋给len,然后又一次遍历数据库表,感觉重复啰嗦了。又不知道怎么改善,网友帮帮……先谢谢了。
帮看看这段代码吧
//为什么运行的时候会出错啊?谢谢rn[code=C/C++][#include rn#include rn#include rn#include rnusing namespace std;rnrnint main()rnrn list clist;rn vector svec;rn char *temp;rn while(cin>>temp)rn clist.push_back(temp);rn svec.assign(clist.begin(),clist.end());rn for(vector::size_type ix=0;ix!=svec.size();++ix)rn cout<
帮看看这段代码,怎么回事
帮看看这段代码,怎么回事rnrn<%rnpathnameSTR="pinlun/123_1.htm"rnIf Dir(pathnameSTR) then rnresponse.redirect pathnameSTRrnelsernresponse.redirect "abc.htm"rnend ifrnrnFunction Dir(pathnameSTR)rnDim objFSOrnSet objFSO = Server.CreateObject("Scripting.FileSystemObject")rnDir = objFSO.FolderExists(pathnameSTR)rnSet objFSO = NothingrnEnd Functionrn%> rnrn我的服务器支持fso,pinlun/123_1.htm也存在,但怎么也转向不到这个文件rn
请帮看看这段代码?
library TmHook; rnrnuses rn SysUtils, rn Classes, rn Windows, rn Messages, rn CommCtrl; rnvar rn hhook: Windows.HHOOK; rn hwndListView: HWND; rn na:array[0..300] of char; rn oldWndProc: Integer; rn$R *.res rnfunction WindowProc(hwnd: HWND; msg: UINT; wp: WPARAM; lp: LPARAM): LRESULT; stdcall; rn begin rn case Msg of rn WM_LBUTTONDOWN: rn MessageBox(hwndListView,'你好!','提示',MB_OK); rn end; rn Result := CallWindowProc(TFNWndProc(oldWndProc), hwnd, msg, wp, lp); rnend; rnfunction TmHookProc(nCode: Integer; wParam: WPARAM; lParam: LPARAM): Integer; stdcall; rnvar rn cwp: PCwpStruct; rn m:TPoint; rnbegin rn Result := 0; rn if (nCode < 0) then rn begin rn Result := CallNextHookEx(hhook, nCode, wParam, lParam); rn exit; rn end; rn cwp := PCwpStruct(lParam); rn if cwp^.message <> WM_COMMAND then rn begin rn Result := CallNextHookEx(hhook, nCode, wParam, lParam); rn exit; rn end; rn GetCursorPos(m); rn GetWindowText(WindowFromPoint(m),na,299); rn if lstrcmpi('发送(S)',na) <>0 then rn begin rn Result := CallNextHookEx(hhook, nCode, wParam, lParam); rn exit; rn end; rn hwndListView:=WindowFromPoint(m); rn oldWndProc := SetWindowLong(hwndListView, GWL_WNDPROC, Integer(@WindowProc)); rn end; rnprocedure Hook(bEnable: Boolean); stdcall; export; rnbegin rn if bEnable then rn begin rn if hhook = 0 then rn begin rn hhook := SetWindowsHookEx(WH_CALLWNDPROC, TmHookProc, HInstance, 0); rn end; rn end rn else rn begin rn if hhook <> 0 then rn begin rn UnhookWindowsHookEx(hhook); rn hhook := 0; rn end; rn end; rnend; rnexports rn Hook; rnbegin rn hhook := 0; rn hwndListView := 0; rn oldWndProc:=0; rnend. rn到底哪里错了,一运行,qq就自动关闭?? rnrnrn我在学子类化,这段代码测试了很久,都没有找出原因?
帮看看这段代码,很少的
<%@ language="java" %>rn<%rn int a;rnrn String b="111";rn a=Integer.parseInt(b);rn out.println(a);rn rn%>rnrn报错!Integer.parseInt(b)这个方法到底怎么回事啊,我查了API,但没看明白
请帮看看这段代码.
function htmlencode2(str)rn dim resultrn dim lrn if isNULL(str) then rn htmlencode2=""rn exit functionrn end ifrn l=len(str)rn result=""rndim irnfor i = 1 to lrn "对返回的内容进行判定,并对其含有<,>,chr(13),chr(34),&,chr(32),chr(9)进行相应的转化,如chr(13)变为 ;也就是回车的HTM代码rn select case mid(str,i,1)rn case "<"rn result=result+"<"rncase ">"rn result=result+">"rn case chr(13)rn result=result+" "rn case chr(34)rn result=result+"""rn case "&"rn result=result+"&"rn case chr(32) rn 'result=result+" "rn if i+1<=l and i-1>0 thenrn if mid(str,i+1,1)=chr(32) or mid(str,i+1,1)=chr(9) or mid(str,i-1,1)=chr(32) or mid(str,i-1,1)=chr(9) then rn result=result+" "rn result=result+" "rn end ifrn elsern result=result+" " rn end ifrn case chr(9)rn result=result+" "rn case elsern result=result+mid(str,i,1)rn end selectrn next rn htmlencode2=resultrn end functionrn%>rn
帮看看这段代码如何解密?
rn rnrn
看看这段SQL代码如何优化下 PK
rn SET @vReturnTime =(SELECT ReturnTime FROM car_arrive_info where ListId = @iListId AND (ReturnTime IS NOT NULL AND ReturnTime<>''))rn SET @iiSn =(SELECT SN FROM CAR_ARRIVE_INFO WHERE ListId=@iListId AND ReturnTime=@vReturnTime)rnrn IF EXISTS (SELECT ReturnTime FROM CAR_ARRIVE_INFO WHERE @vArriveTime < @vReturnTime AND ListId = @iListId AND SN <@iiSn )rn BEGINrn UPDATE CAR_ARRIVE_INFOrn SET ArriveTime = @vArriveTime,Distnce=@iDistnce,State=1,OutTime = @vArriveTimern WHERE ListId = @iListId AND SN = @iSn AND State=0 AND SN <@iiSn AND @vArriveTime < @vReturnTimern ENDrnrn IF EXISTS (SELECT ReturnTime FROM CAR_ARRIVE_INFO WHERE @vArriveTime > @vReturnTime AND ListId = @iListId AND SN >= @iiSn)rn BEGINrn UPDATE CAR_ARRIVE_INFOrn SET ArriveTime = @vArriveTime,Distnce=@iDistnce,State=1,OutTime = @vArriveTime rn WHERE ListId = @iListId AND SN = @iSn AND State=0 AND SN >=@iiSn AND @vArriveTime >= @vReturnTimern END
如何优化这段代码!!!
<%@ Page Language="VB" Debug="True" %>rn<%@ Import Namespace="System.Data" %>rn<%@ Import Namespace="System.Data.SqlClient" %>rn
如何优化这段代码?
Select * from User where Score in(Select Score from UserScore where UserScore <90) and Age<20rn如何优化呢?
如何优化这段代码?
WHERE 数量 >= 1 AND 数量 < 3rnUPDATE abcrnSET p数 = 18rn WHERE 数量 =1rn UPDATE abcrn SET p数 = 19rn WHERE 数量 >= 3 AND 数量 < 6rn UPDATE abcrn SET p数 = 20rn WHERE 数量 >= 6 AND 数量 < 9rn UPDATE abcrn SET p数 = 21rn
这段代码如何优化下?
[code=VB]rn'邮箱和地址排一排rnif pEmail <> "" and pAddress <> "" thenrn address_email = " 邮箱:"&pEmail&" 地址:"&pAddress&""rnelseif pEmail = "" and pAddress <> "" thenrn address_email = "地址:"& pAddress &""rnelseif pEmail <> "" and pAddress = "" thenrn address_email = " 邮箱:"& pEmail &""rnend ifrn[/code]rnrn如果邮箱和地址都有内容,则显示到一个 里,并用空格隔开,如果其中一个为空,则都单独显示rnrn上面代码感觉效率太低,有更好的方法没?
这段代码如何优化?
[code=text]rnrn-- 后端抽取物品数据结构rnGoodsTable =rnrn -- goodsName 物品名称, goodsWeight 物品权重rn rn goodsName = "无",rn goodsWeight = 60,rn ,rn rn goodsName = "倚天剑",rn goodsWeight = 30,rn ,rn rn goodsName = "屠龙刀",rn goodsWeight = 20,rn ,rn rn goodsName = "流星剑",rn goodsWeight = 10,rn rnrnlocal localGoodsTable = GoodsTablernrnlocal function GetAllgoodsWeight() -- 得到物品总权重rn local allGoodsWeightCount = 0rn for _, v in ipairs(localGoodsTable) dorn allGoodsWeightCount = allGoodsWeightCount + v.goodsWeightrn endrn return allGoodsWeightCountrnendrnrnlocal function ChouJiang(randomCount)rn local lastGoodsWeight = 0rn for _, v in ipairs(localGoodsTable) dorn lastGoodsWeight = lastGoodsWeight + v.goodsWeightrn if(lastGoodsWeight >= randomCount) thenrn return vrn endrn endrnendrnrnlocal function main()rn math.randomseed(os.time())rn local allGoodsWeightCount = GetAllgoodsWeight()rn for i = 1, 1000 do -- 抽取1K次rn local randomCount = math.random(1, allGoodsWeightCount)rn print("得到物品:"..ChouJiang(randomCount).goodsName)rn endrnendrnrnmain()rn[/code]
请教,怎样优化这段代码?
俺编写了以下第1段至第8段的代码,以nn30a表的数据对照x1、x2、x3进行分析,虽能解决问题,但太过繁琐,想请教老师们,如何优化这段代码?谢谢。rnrn CLOSE ALLrn clearrn set safe offrn rn CREATE TABLE nn30a (cname c(8),nnewsal n(9,2) ,cont c(8))rnINSERT INTO nn30a VALUES ("hans", 101,"T")rnINSERT INTO nn30a VALUES ("cici", 123, "TW")rnINSERT INTO nn30a VALUES ("mini",119, "T")rnINSERT INTO nn30a VALUES ("jack",123, "T")rnINSERT INTO nn30a VALUES ("marry",92, "TN")rnINSERT INTO nn30a VALUES ("dick", 110, "T")rnINSERT INTO nn30a VALUES ("lee",121, "T")rnINSERT INTO nn30a VALUES ("john", 99,"TN")rnINSERT INTO nn30a VALUES ("king",112, "T")rnINSERT INTO nn30a VALUES ("rose", 102, "T")rnINSERT INTO nn30a VALUES ("sam", 102, "TN")rnINSERT INTO nn30a VALUES ("sany",98, "T")rnINSERT INTO nn30a VALUES ("tom",102, "T")rnINSERT INTO nn30a VALUES ("wick",121, "TW")rnINSERT INTO nn30a VALUES ("monica", 123, "T")rnINSERT INTO nn30a VALUES ("ming",95, "TN")rnINSERT INTO nn30a VALUES ("kinsinger",121, "T")rnINSERT INTO nn30a VALUES ("nixon",96,"T") rn rn FOR i=1 TO 15 rn cComstr="ALTER TABLE nn30a ADD COLUMN ms"+CHRTRAN(STR(i,2),' ','0')+" n(10,2)"rn &cComstrrn ENDFORrnrnrn x1=100 rn x2=102 rn x3=105 rn rn use nn30arn repl all ms01 with x1 for nnewsal<=x1 rn repl all ms02 with x2 for nnewsal<=x2 rn rn *第1段********************************rn repl all ms03 with nnewsal*20/100 for nnewsal>x1 and cont="T " rn repl all ms03 with nnewsal*12/100 for nnewsal>x1 and cont<>"T " rn repl all ms03 with x1*20/100 for nnewsal<=x1 and cont="T " rn repl all ms03 with x1*12/100 for nnewsal<=x1 and cont<>"T " rn repl all ms04 with nnewsal*8/100 for nnewsal>x1 rn repl all ms04 with x1*8/100 for nnewsal<=x1 rn *第2段********************************rn repl all ms05 with nnewsal*2/100 for nnewsal>x1 rn repl all ms05 with x1*2/100 for nnewsal<=x1 rn repl all ms06 with nnewsal*1/100 for nnewsal>x1 and cont="T " rn repl all ms06 with x1*1/100 for nnewsal<=x1 and cont="T " rn rn *第3段********************************rn repl all ms07 with nnewsal*8/100 for nnewsal>x2 and cont="T " rn repl all ms07 with x2*8/100 for nnewsal<=x2 and cont="T " rn repl all ms08 with nnewsal*2/100 for nnewsal>x2 and cont="T " rn repl all ms08 with x2*2/100 for nnewsal<=x2 and cont="T " rn *第4段*******************************rn repl all ms09 with nnewsal*4/100 for nnewsal>x3 and cont<>"T " rn repl all ms09 with x3*4/100 for nnewsal<=x3 and cont<>"T " rn *第5段********************************rn repl all ms10 with nnewsal*0.85/100 for nnewsal>x2 and cont="T " rn repl all ms10 with x2*0.85/100 for nnewsal<=x2 and cont="T " rn *第6段********************************rn repl all ms11 with x3*0.26/100rn *第7段*********************************rn repl all ms12 with nnewsal*0.5/100 for nnewsal>x1 rn repl all ms12 with x1*0.5/100 for nnewsal<=x1 rn *第8段********************************rn rn repl all ms13 with ms03+ms05+ms07+ms09+ms10+ms11+ms12 rn repl all ms14 with ms04+ms06+ms08 rn repl all ms15 with ms13+ms14rn **************************************************rn rn browrn SET SAFETY ONrn CLOSE ALLrn CLEARrn rn rn
请教各位,看看这段代码
CRect rect;rnpDC->SelectStockObject(NULL_BRUSH); rnCRect rectEdage((int)(rect.left),(int)(rect.top),(int)(rect.right),(int)(rect.bottom) );rnpDC->Rectangle(&rectEdage);rn我想画一个矩形,请各位看看上面的代码对吗?,编译也没有错误啊,怎么不能显示呢??
帮看看这段存储过程
对mysql不是很熟。。rn[code=SQL]rnrnDROP PROCEDURE IF EXISTS InsertUserInfo;rncreate PROCEDURE InsertUserInfo() rnBEGIN rn DECLARE i int DEFAULT 0; rn START TRANSACTION; rn DECLARE username VARCHAR(20); rn WHILE i<600000 DO rn set username= concat('test', i);rnINSERT INTO userinforn(rnCompanyId,LoginName,Password,UserType,SurName,GivenName,Gender,DOB,rnIDCardNum,TelOffice,TelMobile,Email,IM1,IM2,Fax,LastLoginTime,LoginCount,rnStatus,Notes,Flag,CreateUser,CreateTime,CreateIPrn)rnVALUESrn(rn0,username,'e10adc3949ba59abbe56e057f20f883e',30,'test','test','M',rn'2010-12-16 00:00:00','440921198406082356','0750-88888888','1369999999','xxx@bvbuy.cn','222222',rn'222222','0750-5555555555','2010-12-16 00:00:00',20,1,'test','M',1,'2010-12-16 00:00:00','192.168.1.90'rn);rnrn set i=i+1; rn END WHILE; rn COMMIT; rnEND rn[/code]rnrnYou have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @username VARCHAR(20); rn WHILE i<600000 DO rn set @u' at line 5
golang的一些使用技巧
// 我是谁已经不重要了,重要的是我们可以一起同行! 来吧, 一起go吧! 1.枚举的实现 const ( freeTime = 5 betTime = 9 openTime = 7 ) 比如 定义字节大小的枚举 const( b = 1&lt;&lt;(10*iota) //1 kb //1024 mb...
Golang之Channel的理解与应用
博客参考自:https://golangbot.com/buffered-channels-worker-pools/ 基础应用 使用channel的阻塞性质作为延时函数。 package main import ( &amp;amp;quot;fmt&amp;amp;quot; ) func hello(done chan bool) { fmt.Println(&amp;amp;quot;Hello world goroutine !&amp;amp;quot;) ...
Golang之消息机制channel
1. 背景:1. 对于以下这段代码:按照想法应该输出0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9但是,输出结果是:0 1 2 3 4 5 6 7 8 92. 原因:在goroutine还未来得及跑loop函数时,主函数main已经退出。解决主函数退出太快最直接的方法是让主函数睡眠一段时间:这次输出结果确实是两趟。可是等待的办法并不好,因为并不知goroutine要...
Golang channel 的实现原理
Channel 是golang语言自身提供的一种非常重要的语言特性, 它是实现任务执行队列、 协程间消息传递、高并发框架的基础。关于channel的用法的文章已经很多, 本文从channel源码的实现的角度, 讨论一下其实现原理。 关于channel放在: src/runtime/chan.go channel的关键的结构体放在hchan里面, 它记录了channel实现的关键信息。 ...
golang channel的设计瑕疵
golang channel深度剖析
Golang Channel 高并发的初始
go中channel是一种重要的引用数据类型,可以看作是管道,可以通过并发的核心单元发送或者接收数据进行通讯。 操作符 &amp;lt;-,箭头指向,即数据的流向,没有指明方向,那么Channel就是双向的,既可以接收数据,也可以发送数据 ch &amp;lt;- v // 发送值到Channel ch中 v := &amp;lt;-ch // 从Channel ch中接收数据,并赋值给v ...
求如何优化这段代码
这个函数的作用就是用mtx来影射rgba的值,把结果保存在rgba数组中rnrgba[0]、rgba[1]、rgba[2]、rgba[3]的值分别代表red green blue alpha,范围在0~255rnmtx的值本来是小数的,但我让它们乘上256转换为int,所以计算到最后有一个>>8的操作rn最终的返回值必须在0~rgba[3]之间,rgba[3]是不变的rnvoid map_rgba(int mtx[4][4], int rgba[4])rnrn int r, g, b;rn r = rgba[0] * mtx[0][0] + rgba[1] * mtx[1][0] + rgba[2] * mtx[2][0] + rgba[3] * mtx[3][0];rn g = rgba[0] * mtx[0][1] + rgba[1] * mtx[1][1] + rgba[2] * mtx[2][1] + rgba[3] * mtx[3][1];rn b = rgba[0] * mtx[0][2] + rgba[1] * mtx[1][2] + rgba[2] * mtx[2][2] + rgba[3] * mtx[3][2];rn rgba[0] = min(max(0, r >> 8), rgba[3] );rn rgba[1] = min(max(0, g >> 8), rgba[3]);rn rgba[2] = min(max(0, b >> 8), rgba[3]);rnrnrnvoid main()rnrn const int nTimes = 1000000;rn int mtx[4][4] = rn 0, 1, 2, 3,rn 4, 5, 6, 7,rn 8, 9, 10,11,rn 12, 13, 14, 15rn ;rn int rgba[4] = 255, 128, 64, 128;rn clock_t t1 = clock();rn for (int i = 0; i < 1000000; i++)rn rn map_rgba(mtx, rgba);rn rn clock_t t2 = clock();rnrn printf("excute %d times, time = %d\n", nTimes, t2 - t1);rn printf("rgb(%d, %d, %d)\n", rgba[0], rgba[1], rgba[2]);rnrn这段代码在我机器(双核,4G内存)上运行耗时为18msrn如何优化map_rgba函数以提高效率呢?rn可以使用MMX SSE 或者汇编,请大侠们把完整代码贴上来。(我对MMX SSE 和汇编都不熟悉的)
请问这段代码如何优化?
for(int m=0;m>16; rn if ( avg >255 ) rn avg = 255; rn *(imageGRAY+m) = (byte)avg; rn rn运行时间大概为2-3ms,计算机重启后,运行时间为1.2ms左右,运行几次后重新回到2-3ms. 如果把这段程序加for循环运行1000次,平均时间大概为1.1ms-1.2ms. rn环境为:E5-1620 V4@3.5GHZ, 32GDDR4, win7 64bit ,VS2010 rn请问大家有啥办法让它稳定在1.2ms吗?谢谢
Golang中Channel的实现原理
CSP模型 要想理解 channel 要先知道 CSP 模型。CSP 是 Communicating Sequential Process 的简称,中文可以叫做通信顺序进程,是一种并发编程模型,由 Tony Hoare 于 1977 年提出。简单来说,CSP 模型由并发执行的实体(线程或者进程)所组成,实体之间通过发送消息进行通信,这里发送消息时使用的就是通道,或者叫 channe...
golang channel阻塞问题解决
先看一段会死锁的代码:package mainimport ( "fmt" )func f1(in chan int) { fmt.Println(<-in) }func main() { out := make(chan int) out <- 2 go f1(out) }单纯的out<-和<-in都会阻塞,只有两个同时进行了,才能继续执行。 这里你看上去
如何优化这段查询代码
winform程序rn有三张表,简单说明如下(Access数据库)rn表A(机器)rn字段: id 区域rn表B(区域)rn字段:id 性质rn表C(负责人)rn字段:id 名称rn实际上的情况要比这个复杂一点,为了说明问题我简化了一下rn每个表的id字段都是各自的主键,我需要做的是在datagridview中将机器id,所属区域,所属区域的负责人显示出来,如果仅仅是这样就好办了,比较麻烦的是表A中的机器可能不属于任何区域(此时区域字段用0填充),也可能属于好几个区域(用,隔开区域id,比如1,2,3),而表B中区域字段可能是空的或者是表c中id字段中的一个值(只有一个)rnrn表Arnid 区域rn1 0rn2 1,2rn3 3rn4 1,3rnrn表Brnid 性质rn1 1rn2 2rn3 rnrn表Crnid 负责人rn1 张三rn2 李四rnrn显示如下rn id 所属区域 负责人rn 1 0 无rn 2 1,2 张三,李四rn 3 3 该区域未指定负责人rn 4 1,3 张三,该区域未指定负责人rnrn我原来的查询方式是遍历表A,如果其所属区域为0则设置变量值为“无”,否则用变量记录所属区域的值,然后用split分开,分别查询该区域id在表b中对应的性质,如果性质为空则设置变量为“该区域未指定负责人”,将所属的每个区域的负责人名称组合到变量中rnrnsql语句如下(程序中字段名为英文,此处为了说明方便写成中文)rn sqlQuery = "select id ,区域 from 表A";rn ds = DataAccess.GetDataSet(sqlQuery, "表A");rn for (int dscount = 0; dscount < ds.Tables[0].Rows.Count; dscount++)rnrn str = "";rnif (ds.Tables[0].Rows[dscount][1].ToString() != "0")//该机器有所属区域rnrn idarea = ds.Tables[0].Rows[dscount][1].ToString().Split(',');rn for (int i = 0; i < idarea .Length; i++)rn rn sql = "select id from 表B where id=" + idarea [i] + "";rn if (DataAccess.QueryData(sql) != "")//该区域有负责人rn rn sql = "select 负责人 from 表C where id =(select 性质 from 表B where id=" + idarea [i] + ")";rn ds2 = DataAccess.GetDataSet(sql, "表B", "表C");rn if (ds2.Tables[0].Rows.Count > 0)rn rn gname = ds2.Tables[0].Rows[0][0].ToString();//区域对应的负责人rn if (idcom == "")rn rn idcom = gname ;rn rn elsern rn idcom = idcom + "," + gname ;rn rn rn rn rnrnstr=ds.Tables[0].Rows[dscount][0].ToString() + " " + ds.Tables[0].Rows[dscount][1].ToString() + " " + idcom;rnrn将组合好的数据添加到界面表格上rn string[] row = str.Split(' ');rn rows.Add(row);//在界面上添加一行数据rn本来是这样直接添加到界面上的,可执行速度太慢,界面象死机一样,然后一下将所有数据一起显示出来。现在改用线程方式,可以一行一行显示,但总体执行时间还是比较长,200多条数据竟然用了50多秒,机器配置不怎么样,内存只有256,但我觉得我的sql语句写的还是有问题的,这样频繁的访问数据库效率肯定低,想请教各位如何能优化这段代码?rnrn
如何优化一下这段代码?
strSql = "delete from aa";rn strSql1 = "delete from aa2";rn ...rn strSql9 = "delete....."rnrn myCommand = new SqlCommand(strSql,myConn);rn myCommand1 = new SqlCommand(strSql1,myConn);rn ....rn myCommand9 = new .....rn try rn rn statusBar2.Text = "正在删除表aa...";rn myCommand.ExecuteNonQuery();rnrn statusBar2.Text = "正在删除表aa2...";rn myCommand1.ExecuteNonQuery();rnrn.....rn statusBar2.Text = "正在删除表aa9...";rn myCommand9.ExecuteNonQuery();rnrn rn statusBar2.Text = "完成...";rn rn catch(System.Exception Exp)rn rn MessageBox.Show ("错误!" + Exp.Message,"错误提示",MessageBoxButtons.OK,MessageBoxIcon.Error);rn return;rn rn finallyrn rn myConn.Close();rn rn rn这种写法太麻烦,要建9个myCommand9(myCommand1-myCommand9),我还不想写存贮过程,因为我想要在状态栏看到状态的变化,(如在每删除一个条件时statusBar2.Text = "正在删除表WapCdr01...";)应如何改近???
Golang学习笔记--channel基础
go在语言层面支持并发编程,也就是goroutine,可以看做一种轻量级的线程。程序启动时,其主函数即在一个单独的goruntine中运行,叫做main goruntine,在程序中通过关键字go跟上函数(支持匿名函数)就可以启动一个新的goroutine,可以叫做sub goruntine。 在基于多线程设计的并发编程模型中,线程间的通信往往通过共享数据来实现,而保证共享数据的一致性非常关键。...
帮看看这段代码,哪里出错了!!
是打印乘法表的,因数都是正确的,就是乘积出错了,乘积全部都是一样的-858993460,请问这个要怎么修改啊?rnrn#includernrnvoid main()rnrn int hang=1,lie;rn int b=hang*lie;rn while (hang<=9)rn rn lie=1;rn while (lie<=hang)rn rn printf("%2.0d*%2.0d=%2.0d\b\b",hang,lie,b);rn lie++;rn rn printf("\b\b\n");rn hang++;rn rn
帮看看这段代码怎么加条件
this.ShowTips= .F. rnSELECT jwxc_reportmrnSET ORDER TO rnGO TOP rnIF !EOF()rn DO FORM zplan LINKED rn zplan.lblName.Caption=Big("正在获取数据,请稍候......")rn zplan.Plan.Min=0rn zplan.Plan.Max=RECCOUNT()rn SCAN rn Vi=RECNO()rn SCATTER MEMVAR rn SELECT tm_jwcxreportrn APPEND BLANK rn GATHER MEMVAR rn REPLACE Vcreportdate WITH jwxc_reportm.reportdate,;rn Vcbc WITH jwxc_reportm.bc,;rn Vcreporter WITH jwxc_reportm.reporter,Vcreportername WITH jwxc_reportm.reportername,Vcdept WITH jwxc_reportm.dept,;rn Vcdeptname WITH jwxc_reportm.deptname,Vcxm WITH jwxc_reportm.xm,Vczysx WITH jwxc_reportm.zysx,Vcxc_date WITH jwxc_reportm.xcrq,;rn Vcclfs WITH jwxc_reportm.clfs,VcJggz WITH jwxc_reportm.Jggz,vid WITH jwxc_reportm.j_id,;rn Vcchecker WITH jwxc_reportm.checker,VccheckerName WITH jwxc_reportm.checkername,Vcremark WITH jwxc_reportm.remark,;rn Vcfinishdate WITH jwxc_reportm.finishdate,Vcxcjg WITH jwxc_reportm.xcjgrn mm1=mm1+1rn zplan.Plan.OBJECT.Value=Virn zplan.lblWait.Caption=Big("已完成")+ALLTRIM(STR(INT(Vi/zplan.Plan.OBJECT.Max*100)))+"%"rn ENDSCAN rn zplan.Release rnENDIF rnSELECT tm_jwcxreportrnGO TOP rnthis.Refresh rn把所有记录都调出来了。。能不能只选择最近一个月的记录。。加个条
帮看看这段代码,不知道怎么回事~
为什么在第二个输入,就是cin>>length时会直接跳过而不进行输入操作呢?rnrnint main()rnrn int length, size;rn char a[100];rn char b[100];rn cout<<"input some defferent characters:\n";rn while(cin.get(a,100))rn rn size = cin.gcount();rn rnrn cout<<"input the length of the queue:\n";rn cin>>length;rnrn calculate(a,b,0,size,length);rn cout<<"sum = "<
如何优化下面这段代码?
for (int i=0;i>8)&REDMASK;rnwdG = ((GETGREENVALNOTRAN(wdPixelSrc)*btTranAlp + GETGREENVALNOTRAN(wdPixelDst)*otherTranAlp/*(255-btTranAlp)*/)>>8)&GREENMASK;rnwdB = ((GETBLUEVALNOTRAN(wdPixelSrc)*btTranAlp + GETBLUEVALNOTRAN(wdPixelDst)*otherTranAlp/*(255-btTranAlp)*/)>>8)&BLUEMASK;rn*(WORD*)( lpBtDstData+nDstBegIdx) = (wdR|wdG|wdB); rnrn nSrcBegIdx=nSrcBegIdx+2;rn nDstBegIdx=nDstBegIdx+2;rn nSrcBegIdxAlp++;rn rn nDstBegIdx = (nDstBegIdxbk=nDstBegIdxbk+nLineBytesDst);rn nSrcBegIdx = (nSrcBegIdxbk=nSrcBegIdxbk+nLineBytesSrc);rn nSrcBegIdxAlp = (nSrcBegIdxAlpbk = nSrcBegIdxAlpbk+m_stImageAttribute.m_dwWidth);rn rn由于上面这段代码有二次循环,每次都要进行6次乘法运算,如果是800*480的屏的话,刷新会非常慢,请问各位有什么好的方法进行优化吗?
这段代码为什么会出错?帮看看
#include "stdio.h"rn#include "stdlib.h"rn#include "time.h"rn#include "conio.h"rn#include "memory.h"rn#include "string.h"rnrnrnmain()rnrn char timebuf[9],datebuf[9];rn char now[9];rn int tmp1,tmp2;rn tmp1=tmp2=0;rn _strtime(timebuf);rn printf("\n%s",timebuf);rn _strdate(datebuf);rn printf("\n%s",datebuf);rn strcpy(timebuf,"16:28:00");rn strcpy(datebuf,"09/18/01");rn tmp1=2000+atoi(datebuf[6])*10+atoi(datebuf[7]); ///?????rn memcpy(now,&tmp1,2);rn getch();rnrnrnrn单步跟踪到问好的语句处就不行了
请高手帮菜鸟看看这段代码!!!!!!!!
今天做做练习题时发现了一个问题:rn这道题是将一个数据以三种格式输出,可是最后一个方法,即以科学计数法输出时却出现问题,代码如下:rn[code=Java]public class DoubleOutrnrn public static void write(double amount)rnrn if(amount>0)rnrn System.out.print('$');rn writePositive(amount);rnrn elsernrn double positiveAmount=-amount;rn System.out.print('s');rn System.out.print('-');rn writePositive(positiveAmount);rnrn rnrn //end write()rnrn private static void writePositive(double amount)rnrn int allCents=(int)(Math.round(amount*100));rn int dollars=allCents/100;rn int cents=allCents%100;rn System.out.print(dollars);rn System.out.print('.');rn if(cents<10)rnrn System.out.print('0');rn System.out.print(cents);rnrn elsernrn System.out.print(cents);rnrn rnrn //end writePositivernrn public static void writeln(double amount)rnrn write(amount);rn System.out.println();rnrn //end writelnrnrn public static void write(double number,int digit)rnrn if(number>=0)rnrn writePositive(number,digit);rnrn elsernrn double positiveNumber=-number;rnrn System.out.print("-");rnrn writePositive(positiveNumber,digit);rnrn //end if-elsernrn //end write()rnrn private static void writePositive(double number,int digit)rnrn double digitCopy=digit;rnrn int finalNumber=(int)Math.round(number*Math.pow(10.0,digitCopy));rnrn int integerPart=finalNumber/(int)Math.pow(10.0,digitCopy);rnrn int decimalPart=finalNumber%(int)Math.pow(10.0,digitCopy);rnrn System.out.print(integerPart);rnrn System.out.print(".");rnrn int count=0;rnrn int decimalPartCopy=decimalPart;rnrn while(decimalPartCopy<(int)Math.pow(10.0,digitCopy))rnrn if(decimalPartCopy==0)rnrn decimalPartCopy=(decimalPartCopy+1)*10;rnrn elsernrn decimalPartCopy=decimalPartCopy*10;rnrn //end if-elsernrn count++;rnrn //end whilernrn for(int i=1;i=0)rn rn scienceWritePositive(number);rn rn elsern rn double positiveNumber=-number;rn rn System.out.print("-");rn rn scienceWritePositive(positiveNumber);rn rn rn rn //end scienceWrite()rnrn private static void scienceWritePositive(double number)rnrn String numberCopy=Double.toString(number);rnrn int theIndexOfThePoint=numberCopy.indexOf(".");rnrn int length=numberCopy.length();rnrn int theIndexOfTheFirst=0;rnrn char theFirst=numberCopy.charAt(theIndexOfTheFirst);rnrn while((theFirst=='0')||(theFirst=='.'))rn rn theIndexOfTheFirst++;rn rn theFirst=numberCopy.charAt(theIndexOfTheFirst);rn rn rnrn int theNumberAfterE=theIndexOfTheFirst-theIndexOfThePoint;rnrn double theFormatedNumber=number/Math.pow(10.0, theNumberAfterE);rnrn System.out.print(theFormatedNumber);rnrn System.out.print("e");rnrn System.out.print(-theNumberAfterE);rn rn //end scienceWritePositive()rn rn public static void scienceWriteln(double number)rnrn scienceWritePositive(number);rnrn System.out.println("");rnrn //end scienceWriteln()rnrn public static void main(String[] args)rnrn DoubleOut.writeln(0.052165);rnrn DoubleOut.writeln(0.052165,3);rnrn DoubleOut.scienceWriteln(0.052165);rnrn //end main()rn[/code]rnrn第一个输出$0.05,没问题;rn第二个输出0.052,没问题;rn但第三个却输出5.2165E-4e-2(我想得到的结果是输出5.2165e-2)那么请问高手中间的E-4是怎么回事,怎么会输出这个东西来?
帮看看这段代码的问题在哪里?
[code=HTML]rnrnrnrn rn 无标题文档rn rnrnrnrnrnrnrn[/code]rnrn第一个参数: 提示内容rn第二个参数: 图片显示rn第三个参数: 关闭时间rnrn弹出提示框自动关闭,第一次执行还正常,但第二次执行时发现时间还没有到就关,rn执行的次数越多,关闭的就越快,怎么修改一下啊,我对JS基本不懂。。。。。rn先谢了
相关热词 c# 线程顺序 c#昨天当前时间 c# 多进程 锁 c#mysql图片存取 c# ocx 委托事件 c# 读取类的属性和值 c# out 使用限制 c#获取url的id c#怎么进行分页查询 c# update 集合