Skip to content

Correctly call CloseChannel in the destructor of a channel #8248

Closed
@wangkuiyi

Description

@wangkuiyi

I just moved @abhinavarora 's PR description into this issue. Thanks to @abhinavarora who discovered this bug.


Problem

The problem here is that if we call the destructor of channel (delete ch) before closing the channel, then the unit test program crashes. We need to make sure that deleting a channel has clean semantics and does not cause program crash.

Cause

On investigating the cause, we found that once the destructor closes the channel, it does not wait for the blocked read and write threads. So in this case, it is likely that we end up destroying the mutex(owned by the channel), when some other thread has locked it. As per the CPP Reference for std::mutex, The behavior of a program is undefined if a mutex is destroyed while still owned by any threads, or a thread terminates while owning a mutex.

Solution

The solution that I and @chengduoZH discussed yesterday was to use read and write reference counters in the channel. When a channel destructor is called, it should wait for readers and writers to return before destroying itself and the mutex. It should block till the counter for readers and writers is not 0.

Thanks to @chengduoZH for investigating and discussing the problem with me.

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions