how to use thread

本文探讨了在程序中使用线程显示工作进度时遇到的同步问题。原本期望线程能够与主程序并行运行,但实际上线程仅短暂运行便被主程序抢占资源。为解决该问题,作者将工作负载拆分为独立线程,实现了真正的并行执行。

Just got a problem which wasted me some time. The problem is just:

 

Regarding a procedure A, which mainly implements a work B, I want to use a progress bar to show the progress of the work of B, because A need to run a lot of sub functions and take a lot of time. So inside A, right before executing the code directly related to B's work, I insert a few code to create a thread C to display the progress of B, and after the code of creating the thread C, I continue to put A's original code.

 

I thought C will work with A's code at the same time(sychronization), since it is thread. However the result is, although thread C starts to work, but just for one second, then A's code takes over CPU until A gets finished, and then B continues. This makes using thread C no sense.

 

Then I found the reason: because thread C is created inside the code of A, then CPU have more priority for A. It always tries to finish more work of  A.

 

Solution:

I put the code in A related to work B out and make it a separate thread D to do the work. Then in procedure A, I create the thread C at first, and then create thread D (which does the work B). Now these two threads have the same prority, and then their run are sychoronized.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值