在过去的几天里,我一直试图通过重构我的一个命令行实用程序来解决Golang的并发问题,但我陷入了困境.
这是原始代码(主分支).
这是具有并发性的分支(x_concurrent分支).
当我执行并发代码时go run jira_open_comment_emailer.go
,defer wg.Done()
如果将JIRA问题添加到此处的通道,则永远不会执行,这会导致我wg.Wait()
永远挂起.
这个想法是我有大量的JIRA问题,我想为每个问题分拆一个goroutine,看看它是否有我需要回应的评论.如果是这样,我想将它添加到某个结构(我在一些研究后选择了一个频道),我可以稍后从队列中读取以构建电子邮件提醒.
这是代码的相关部分:
// Given an issue, determine if it has an open comment
// Returns true if there is an open comment on the issue, otherwise false
func getAndProcessComments(issue Issue, channel chan<- Issue, wg *sync.WaitGroup) {
// Decrement the wait counter when the function returns
defer wg.Done()
needsReply := false
// Loop over the comments in the issue
for _, comment := range …
Run Code Online (Sandbox Code Playgroud) 最初,我的代码看起来像这样:
my @departments = @{$opts->{'d'}} if $opts->{'d'};
Run Code Online (Sandbox Code Playgroud)
我想if
根据Perl Best Practices重构内联语句,所以现在我有了以下代码:
my @departments;
if( $opts->{'d'} )
{
@departments = @{$opts->{'d'} };
}
Run Code Online (Sandbox Code Playgroud)
$opts
只是一个哈希引用,可能有一个数组引用作为键的值.
我想做类似以下的事情来保持代码在一行:
my @departments = $opts->{'d'} ? @{$opts->{'d'}} : undef;
Run Code Online (Sandbox Code Playgroud)
但显然,这只会使一个元素@departments
具有价值undef
.
我以这种方式执行此操作的原因是因为我后来想要检查
if( @departments )
{
my $department_string = join( q{,}, @departments );
$big_string . $department_string;
}
Run Code Online (Sandbox Code Playgroud)
动态添加到字符串.