lewissbaker / cppcoro

A library of C++ coroutine abstractions for the coroutines TS
MIT License
3.43k stars 472 forks source link

Data race, detected by tsan #209

Open alephonea opened 2 years ago

alephonea commented 2 years ago

The following code snippet has a race condition, according to thread sanitizer.

$ cat race.cpp

#include <cppcoro/static_thread_pool.hpp>
#include <cppcoro/sync_wait.hpp>
#include <cppcoro/task.hpp>

int main(int argc, char* argv[]) {
  cppcoro::static_thread_pool tp(1);

  auto t = [&tp]() -> cppcoro::task<> {
    co_await tp.schedule();
    co_return;
  }();

  cppcoro::sync_wait(t);

  return 0;
}
$ clang++ -fsanitize=thread -g -O0 -stdlib=libc++ -std=c++2a -isystem ~/repo/cppcoro/include -c race.cpp
$ clang++ -ltsan -stdlib=libc++ race.o -o race ~/repo/cppcoro/build/linux_x64_clang10.0.0_debug/lib/libcppcoro.a -lpthread
$ ./race
WARNING: ThreadSanitizer: data race (pid=483450)
  Write of size 8 at 0x7b20000000f8 by thread T1:
    #0 cppcoro::detail::sync_wait_task<void> cppcoro::detail::make_sync_wait_task<cppcoro::task<void>&, void, 0>(cppcoro::task<void>&) /home/dmitry/repo/cppcoro/include/cppcoro/detail/sync_wait_task.hpp:292 (race+0x403d0e)
    #1 main::$_0::operator()() const /tmp/race.cpp:9 (race+0x40305a)
    #2 std::experimental::coroutines_v1::coroutine_handle<void>::resume() /usr/lib/llvm-10/bin/../include/c++/v1/experimental/coroutine:121 (race+0x406afe)
    #3 cppcoro::static_thread_pool::run_worker_thread(unsigned int) lib/static_thread_pool.cpp:490 (race+0x407750)

  Previous write of size 8 at 0x7b20000000f8 by main thread:
    #0 operator new(unsigned long) ../../../../src/libsanitizer/tsan/tsan_new_delete.cpp:64 (libtsan.so.0+0x8c032)
    #1 cppcoro::detail::sync_wait_task<void> cppcoro::detail::make_sync_wait_task<cppcoro::task<void>&, void, 0>(cppcoro::task<void>&) /home/dmitry/repo/cppcoro/include/cppcoro/detail/sync_wait_task.hpp:292 (race+0x40553a)
    #2 cppcoro::awaitable_traits<cppcoro::task<void>&, void>::await_result_t cppcoro::sync_wait<cppcoro::task<void>&>(cppcoro::task<void>&) /home/dmitry/repo/cppcoro/include/cppcoro/sync_wait.hpp:28 (race+0x404af4)
    #3 main /tmp/race.cpp:14 (race+0x402560)